From a27447d7cfb4ea2f31fd0dcce13dc4be23abb6eb Mon Sep 17 00:00:00 2001 From: Michael Carlstrom Date: Sat, 29 Jun 2024 19:27:59 -0400 Subject: [PATCH] Add Literal support for docstrings (#17441) (Explain how this PR changes mypy.) Updates the is_valid_type regex to include quotes and . --- mypy/stubdoc.py | 2 +- mypy/stubgenc.py | 1 + mypy/test/teststubgen.py | 11 +++++++++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/mypy/stubdoc.py b/mypy/stubdoc.py index 8c0a4dab696f..928d024514f3 100644 --- a/mypy/stubdoc.py +++ b/mypy/stubdoc.py @@ -20,7 +20,7 @@ Sig: _TypeAlias = Tuple[str, str] -_TYPE_RE: Final = re.compile(r"^[a-zA-Z_][\w\[\], ]*(\.[a-zA-Z_][\w\[\], ]*)*$") +_TYPE_RE: Final = re.compile(r"^[a-zA-Z_][\w\[\], .\"\']*(\.[a-zA-Z_][\w\[\], ]*)*$") _ARG_NAME_RE: Final = re.compile(r"\**[A-Za-z_][A-Za-z0-9_]*$") diff --git a/mypy/stubgenc.py b/mypy/stubgenc.py index bacb68f6d1c7..0aa6088a4e02 100755 --- a/mypy/stubgenc.py +++ b/mypy/stubgenc.py @@ -252,6 +252,7 @@ def __init__( "Iterable", "Iterator", "List", + "Literal", "NamedTuple", "Optional", "Tuple", diff --git a/mypy/test/teststubgen.py b/mypy/test/teststubgen.py index 3669772854cb..05a3809179bd 100644 --- a/mypy/test/teststubgen.py +++ b/mypy/test/teststubgen.py @@ -1357,6 +1357,17 @@ def test_is_valid_type(self) -> None: assert is_valid_type("List[int]") assert is_valid_type("Dict[str, int]") assert is_valid_type("None") + assert is_valid_type("Literal[26]") + assert is_valid_type("Literal[0x1A]") + assert is_valid_type('Literal["hello world"]') + assert is_valid_type('Literal[b"hello world"]') + assert is_valid_type('Literal[u"hello world"]') + assert is_valid_type("Literal[True]") + assert is_valid_type("Literal[Color.RED]") + assert is_valid_type("Literal[None]") + assert is_valid_type( + 'Literal[26, 0x1A, "hello world", b"hello world", u"hello world", True, Color.RED, None]' + ) assert not is_valid_type("foo-bar") assert not is_valid_type("x->y") assert not is_valid_type("True")