diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index c48f3da51f85..d5461d2366f6 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -5257,7 +5257,14 @@ class LongName(Generic[T]): ... if alias_definition: return AnyType(TypeOfAny.special_form) # The _SpecialForm type can be used in some runtime contexts (e.g. it may have __or__). - return self.named_type("typing._SpecialForm") + special_form = self.named_type("typing._SpecialForm") + if not alias.no_args: + # Parameterized special forms such as Literal[...] expose __args__ at runtime. + any_type = AnyType(TypeOfAny.special_form) + return special_form.copy_with_extra_attr( + "__args__", self.chk.named_generic_type("builtins.tuple", [any_type]) + ) + return special_form def split_for_callable( self, t: CallableType, args: Sequence[Type], ctx: Context diff --git a/test-data/unit/check-literal.test b/test-data/unit/check-literal.test index b54db1f33fa5..5b6149b29de2 100644 --- a/test-data/unit/check-literal.test +++ b/test-data/unit/check-literal.test @@ -3164,3 +3164,15 @@ bar: Literal[ ] reveal_type(bar) # N: Revealed type is "Literal['duration[s][pyarrow]'] | Literal['duration[ms][pyarrow]']" [builtins fixtures/primitives.pyi] + +[case testLiteralArgsAttribute] +from typing import Literal + +Key = Literal["a", "b", "c"] +reveal_type(Key.__args__) # N: Revealed type is "builtins.tuple[Any, ...]" +for key in Key.__args__: + reveal_type(key) # N: Revealed type is "Any" +Key.__bogus__ # E: "" has no attribute "__bogus__" +Literal.__args__ # E: "" has no attribute "__args__" +[builtins fixtures/tuple.pyi] +[typing fixtures/typing-full.pyi]