From b202f3069a7c8c2f64b6bcc6a1f63794878d6c9d Mon Sep 17 00:00:00 2001 From: sobolevn Date: Mon, 22 Jul 2024 22:44:37 +0300 Subject: [PATCH] Fix `typing.TypeAliasType` being undefined on python < 3.12 (#17558) Closes #17554 CC @JukkaL Refs https://github.com/python/mypy/pull/17320 --- mypy/checkexpr.py | 10 ++++++++-- test-data/unit/check-type-aliases.test | 11 ++++++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index ad1b416a0227..9dee743ad406 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -4679,7 +4679,7 @@ def visit_type_application(self, tapp: TypeApplication) -> Type: """ if isinstance(tapp.expr, RefExpr) and isinstance(tapp.expr.node, TypeAlias): if tapp.expr.node.python_3_12_type_alias: - return self.named_type("typing.TypeAliasType") + return self.type_alias_type_type() # Subscription of a (generic) alias in runtime context, expand the alias. item = instantiate_type_alias( tapp.expr.node, @@ -4743,7 +4743,7 @@ class LongName(Generic[T]): ... y = cast(A, ...) """ if alias.python_3_12_type_alias: - return self.named_type("typing.TypeAliasType") + return self.type_alias_type_type() if isinstance(alias.target, Instance) and alias.target.invalid: # type: ignore[misc] # An invalid alias, error already has been reported return AnyType(TypeOfAny.from_error) @@ -5863,6 +5863,12 @@ def named_type(self, name: str) -> Instance: """ return self.chk.named_type(name) + def type_alias_type_type(self) -> Instance: + """Returns a `typing.TypeAliasType` or `typing_extensions.TypeAliasType`.""" + if self.chk.options.python_version >= (3, 12): + return self.named_type("typing.TypeAliasType") + return self.named_type("typing_extensions.TypeAliasType") + def is_valid_var_arg(self, typ: Type) -> bool: """Is a type valid as a *args argument?""" typ = get_proper_type(typ) diff --git a/test-data/unit/check-type-aliases.test b/test-data/unit/check-type-aliases.test index 6f9e9eda1d02..c7b9694a9188 100644 --- a/test-data/unit/check-type-aliases.test +++ b/test-data/unit/check-type-aliases.test @@ -1074,7 +1074,7 @@ x: TestType = 42 y: TestType = 'a' z: TestType = object() # E: Incompatible types in assignment (expression has type "object", variable has type "Union[int, str]") -reveal_type(TestType) # N: Revealed type is "typing.TypeAliasType" +reveal_type(TestType) # N: Revealed type is "typing_extensions.TypeAliasType" TestType() # E: "TypeAliasType" not callable class A: @@ -1084,6 +1084,15 @@ yc: A.ClassAlias = "" # E: Incompatible types in assignment (expression has typ [builtins fixtures/tuple.pyi] [typing fixtures/typing-full.pyi] +[case testTypeAliasTypePython311] +# flags: --python-version 3.11 +# Pinning to 3.11, because 3.12 has `TypeAliasType` +from typing_extensions import TypeAliasType + +TestType = TypeAliasType("TestType", int) +x: TestType = 1 +[builtins fixtures/tuple.pyi] + [case testTypeAliasTypeInvalid] from typing_extensions import TypeAliasType