[case testSimpleTypeAlias] import typing i = int def f(x: i) -> None: pass f(1) f('') # E: Argument 1 to "f" has incompatible type "str"; expected "int" [targets __main__, __main__.f] [case testUnionTypeAlias] from typing import Union U = Union[int, str] def f(x: U) -> None: pass f(1) f('') f(()) # E: Argument 1 to "f" has incompatible type "tuple[()]"; expected "int | str" [targets __main__, __main__.f] [builtins fixtures/tuple.pyi] [case testTupleTypeAlias] from typing import Tuple T = Tuple[int, str] def f(x: T) -> None: pass f((1, 'x')) f(1) # E: Argument 1 to "f" has incompatible type "int"; expected "tuple[int, str]" [targets __main__, __main__.f] [builtins fixtures/tuple.pyi] [case testCallableTypeAlias] from typing import Callable A = Callable[[int], None] f: A f(1) f('') # E: Argument 1 has incompatible type "str"; expected "int" [targets __main__] [case testListTypeAlias] from typing import List A = List[int] def f(x: A) -> None: pass f([1]) f(['x']) # E: List item 0 has incompatible type "str"; expected "int" [builtins fixtures/list.pyi] [targets __main__, __main__.f] [case testAnyTypeAlias] from typing import Any A = Any def f(x: A) -> None: x.foo() f(1) f('x') [case testNoReturnTypeAlias] # https://github.com/python/mypy/issues/11903 from typing import NoReturn Never = NoReturn a: Never # Used to be an error here def f(a: Never): ... f(5) # E: Argument 1 to "f" has incompatible type "int"; expected "Never" [case testImportUnionAlias] import typing from _m import U def f(x: U) -> None: pass f(1) f('x') f(()) # E: Argument 1 to "f" has incompatible type "tuple[()]"; expected "int | str" [file _m.py] from typing import Union U = Union[int, str] [builtins fixtures/tuple.pyi] [case testProhibitReassigningAliases] A = float if int(): A = int # E: Cannot assign multiple types to name "A" without an explicit "type[...]" annotation [out] [case testProhibitReassigningSubscriptedAliases] from typing import Callable A = Callable[[], float] if int(): A = Callable[[], int] \ # E: Cannot assign multiple types to name "A" without an explicit "type[...]" annotation \ # E: Value of type "int" is not indexable # the second error is because of `Callable = 0` in lib-stub/typing.pyi [builtins fixtures/list.pyi] [out] [case testProhibitReassigningGenericAliases] from typing import TypeVar, Union, Tuple T = TypeVar('T') A = Tuple[T, T] if int(): A = Union[T, int] # E: Cannot assign multiple types to name "A" without an explicit "type[...]" annotation [builtins fixtures/tuple.pyi] [typing fixtures/typing-full.pyi] [case testProhibitUsingVariablesAsTypesAndAllowAliasesAsTypes] from typing import TypeVar, Sequence, Type T = TypeVar('T') A: Type[float] = int if int(): A = float # OK x: A # E: Variable "__main__.A" is not valid as a type \ # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases def bad(tp: A) -> None: # E: Variable "__main__.A" is not valid as a type \ # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases pass Alias = int GenAlias = Sequence[T] def fun(x: Alias) -> GenAlias[int]: pass [out] [case testCorrectQualifiedAliasesAlsoInFunctions] from typing import TypeVar, Generic T = TypeVar('T') S = TypeVar('S') class X(Generic[T]): A = X[S] def f(self) -> X[T]: pass a: X[T] b: A = a c: A[T] = a d: A[int] = a # E: Incompatible types in assignment (expression has type "X[T]", variable has type "X[int]") def g(self) -> None: a: X[T] b: X.A = a c: X.A[T] = a d: X.A[int] = a # E: Incompatible types in assignment (expression has type "X[T]", variable has type "X[int]") def g(arg: X[int]) -> None: p: X[int] = arg.f() q: X.A = arg.f() r: X.A[str] = arg.f() # E: Incompatible types in assignment (expression has type "X[int]", variable has type "X[str]") [out] [case testProhibitBoundTypeVariableReuseForAliases] from typing import TypeVar, Generic, List T = TypeVar('T') class C(Generic[T]): A = List[T] # E: Can't use bound type variable "T" to define generic alias x: C.A reveal_type(x) # N: Revealed type is "builtins.list[Any]" def f(x: T) -> T: A = List[T] # E: Can't use bound type variable "T" to define generic alias return x [builtins fixtures/list.pyi] [out] [case testTypeAliasInBuiltins] def f(x: bytes): pass bytes f(1) # E: Argument 1 to "f" has incompatible type "int"; expected "str" [builtins fixtures/alias.pyi] [case testEmptyTupleTypeAlias] from typing import Tuple, Callable EmptyTuple = Tuple[()] x: EmptyTuple reveal_type(x) # N: Revealed type is "tuple[()]" EmptyTupleCallable = Callable[[Tuple[()]], None] f: EmptyTupleCallable reveal_type(f) # N: Revealed type is "def (tuple[()])" [builtins fixtures/list.pyi] [case testForwardTypeAlias] def f(p: 'Alias') -> None: pass reveal_type(f) # N: Revealed type is "def (p: builtins.int)" Alias = int [out] [case testForwardTypeAliasGeneric] from typing import TypeVar, Tuple def f(p: 'Alias[str]') -> None: pass reveal_type(f) # N: Revealed type is "def (p: tuple[builtins.int, builtins.str])" T = TypeVar('T') Alias = Tuple[int, T] [builtins fixtures/tuple.pyi] [out] [case testRecursiveAliasesErrors1] from typing import Type, Callable, Union def test() -> None: A = Union[A, int] # E: Cannot resolve name "A" (possible cyclic definition) \ # N: Recursive types are not allowed at function scope B = Callable[[B], int] # E: Cannot resolve name "B" (possible cyclic definition) \ # N: Recursive types are not allowed at function scope C = Type[C] # E: Cannot resolve name "C" (possible cyclic definition) \ # N: Recursive types are not allowed at function scope [case testRecursiveAliasesErrors2] # flags: --disable-error-code=used-before-def from typing import Type, Callable, Union def test() -> None: A = Union[B, int] B = Callable[[C], int] C = Type[A] x: A reveal_type(x) [out] main:5: error: Cannot resolve name "A" (possible cyclic definition) main:5: note: Recursive types are not allowed at function scope main:5: error: Cannot resolve name "B" (possible cyclic definition) main:6: error: Cannot resolve name "B" (possible cyclic definition) main:6: note: Recursive types are not allowed at function scope main:6: error: Cannot resolve name "C" (possible cyclic definition) main:7: error: Cannot resolve name "C" (possible cyclic definition) main:7: note: Recursive types are not allowed at function scope main:9: note: Revealed type is "Any | builtins.int" [case testDoubleForwardAlias] # flags: --disable-error-code=used-before-def from typing import List x: A A = List[B] B = List[int] reveal_type(x) # N: Revealed type is "builtins.list[builtins.list[builtins.int]]" [builtins fixtures/list.pyi] [out] [case testDoubleForwardAliasWithNamedTuple] # flags: --disable-error-code=used-before-def from typing import List, NamedTuple x: A A = List[B] class B(NamedTuple): x: str reveal_type(x[0].x) # N: Revealed type is "builtins.str" [builtins fixtures/list.pyi] [out] [case testJSONAliasApproximation] from typing import List, Union, Dict def test() -> None: x: JSON # E: Cannot resolve name "JSON" (possible cyclic definition) \ # N: Recursive types are not allowed at function scope JSON = Union[int, str, List[JSON], Dict[str, JSON]] # E: Cannot resolve name "JSON" (possible cyclic definition) \ # N: Recursive types are not allowed at function scope reveal_type(x) # N: Revealed type is "Any" if isinstance(x, list): reveal_type(x) # N: Revealed type is "builtins.list[Any]" [builtins fixtures/isinstancelist.pyi] [out] [case testForwardRefToTypeVar] # flags: --disable-error-code=used-before-def from typing import TypeVar, List reveal_type(a) # N: Revealed type is "builtins.list[builtins.int]" a: A[int] A = List[T] T = TypeVar('T') [builtins fixtures/list.pyi] [out] [case testFunctionForwardRefAlias] from typing import List, TypeVar T = TypeVar('T') def f(x: T) -> List[T]: y: A[T] reveal_type(y) # N: Revealed type is "builtins.list[T`-1]" return [x] + y A = List[T] [builtins fixtures/list.pyi] [out] [case testFunctionForwardRefAlias2] from typing import List, TypeVar def f() -> None: X = List[int] x: A[X] reveal_type(x) # N: Revealed type is "builtins.list[builtins.list[builtins.int]]" T = TypeVar('T') A = List[T] [builtins fixtures/list.pyi] [out] [case testNoneAlias] from typing import Union void = type(None) x: void reveal_type(x) # N: Revealed type is "None" y: Union[int, void] reveal_type(y) # N: Revealed type is "builtins.int | None" [builtins fixtures/bool.pyi] [case testNoneAliasStrict] from typing import Optional, Union void = type(None) x: int y: Union[int, void] z: Optional[int] x = y # E: Incompatible types in assignment (expression has type "int | None", variable has type "int") y = z [builtins fixtures/bool.pyi] [case testAliasToTupleAndCallable] from typing import Callable, Tuple C = Callable T = Tuple c: C t: T reveal_type(c) # N: Revealed type is "def (*Any, **Any) -> Any" reveal_type(t) # N: Revealed type is "builtins.tuple[Any, ...]" bad: C[int] # E: Bad number of arguments for type alias, expected 0, given 1 also_bad: T[int] # E: Bad number of arguments for type alias, expected 0, given 1 [builtins fixtures/tuple.pyi] [case testAliasRefOnClass] from typing import Generic, TypeVar, Type T = TypeVar('T') class C(Generic[T]): pass class N: A = C[T] B = C[int] x: N.A[C] reveal_type(x) # N: Revealed type is "__main__.C[__main__.C[Any]]" xx = N.A[C]() reveal_type(xx) # N: Revealed type is "__main__.C[__main__.C[Any]]" y = N.A() reveal_type(y) # N: Revealed type is "__main__.C[Any]" M = N b = M.A[int]() reveal_type(b) # N: Revealed type is "__main__.C[builtins.int]" n: Type[N] w = n.B() reveal_type(w) # N: Revealed type is "__main__.C[builtins.int]" [out] [case testTypeAliasesToNamedTuple] from nt import C, D, E A1 = C A2 = D A3 = E class Cls: A1 = C A2 = D A3 = E A1('no') # E: Argument 1 to "C" has incompatible type "str"; expected "int" a1 = A1(1) reveal_type(a1) # N: Revealed type is "tuple[builtins.int, fallback=nt.C]" A2(0) # E: Argument 1 to "D" has incompatible type "int"; expected "str" a2 = A2('yes') reveal_type(a2) # N: Revealed type is "tuple[builtins.str, fallback=nt.D]" a3 = A3() reveal_type(a3) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=nt.E]" Cls.A1('no') # E: Argument 1 has incompatible type "str"; expected "int" ca1 = Cls.A1(1) reveal_type(ca1) # N: Revealed type is "tuple[builtins.int, fallback=nt.C]" Cls.A2(0) # E: Argument 1 has incompatible type "int"; expected "str" ca2 = Cls.A2('yes') reveal_type(ca2) # N: Revealed type is "tuple[builtins.str, fallback=nt.D]" ca3 = Cls.A3() reveal_type(ca3) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=nt.E]" [file nt.pyi] from typing import NamedTuple, Tuple class C(NamedTuple): x: int D = NamedTuple('D', [('y', str)]) class E(Tuple[int, str]): pass [builtins fixtures/tuple.pyi] [out] [case testTypeAliasesToAny] from typing import Any A = Any A # this should not fail [out] [case testDoubleImportsOfAnAlias] from b import * from c import * [file b.py] from a import A [file c.py] from a import A [file a.py] A = int [out] [case testDoubleImportsOfAnAlias2] from b import A from c import A [file b.py] from a import A [file c.py] from a import A [file a.py] A = int [out] [case testDoubleImportsOfAnAlias3] from b import * from c import * [file b.py] from a import A [file c.py] from a import A [file a.py] from typing import Union A = Union[None] [out] [case testAliasToClassMethod] from typing import TypeVar, Generic, Union, Type T = TypeVar('T', bound='C') MYPY = False if MYPY: test = classmethod class C: @test def meth(cls: Type[T], arg: int) -> Union[T, int]: ... class D(C): ... reveal_type(D.meth(1)) # N: Revealed type is "__main__.D | builtins.int" reveal_type(D().meth(1)) # N: Revealed type is "__main__.D | builtins.int" [builtins fixtures/classmethod.pyi] [out] [case testAliasInImportCycle] # cmd: mypy -m t t2 [file t.py] MYPY = False if MYPY: from t2 import A x: A [file t2.py] import t from typing import Callable A = Callable[[], None] [builtins fixtures/bool.pyi] [out] [case testAliasInImportCycle2] import a [file a.pyi] from b import Parameter class _ParamType: p: Parameter _ConvertibleType = _ParamType def convert_type(ty: _ConvertibleType): ... [file b.pyi] from a import _ConvertibleType class Parameter: type: _ConvertibleType [out] [case testAliasInImportCycle3] # cmd: mypy -m t t2 [file t.py] MYPY = False if MYPY: from t2 import A x: A reveal_type(x) # N: Revealed type is "t2.D" reveal_type(A) # N: Revealed type is "def () -> t2.D" A() [file t2.py] import t class D: pass A = D [builtins fixtures/bool.pyi] [out] [case testFlexibleAlias1] from typing import TypeVar, List, Tuple from mypy_extensions import FlexibleAlias T = TypeVar('T') U = TypeVar('U') AnInt = FlexibleAlias[T, int] x: AnInt[str] reveal_type(x) # N: Revealed type is "builtins.int" TwoArgs = FlexibleAlias[Tuple[T, U], bool] TwoArgs2 = FlexibleAlias[Tuple[T, U], List[U]] def welp(x: TwoArgs[str, int]) -> None: reveal_type(x) # N: Revealed type is "builtins.bool" def welp2(x: TwoArgs2[str, int]) -> None: reveal_type(x) # N: Revealed type is "builtins.list[builtins.int]" Id = FlexibleAlias[T, T] def take_id(x: Id[int]) -> None: reveal_type(x) # N: Revealed type is "builtins.int" def id(x: Id[T]) -> T: return x # TODO: This doesn't work and maybe it should? # Indirection = AnInt[T] # y: Indirection[str] # reveal_type(y) # E : Revealed type is "builtins.int" # But this does Indirection2 = FlexibleAlias[T, AnInt[T]] z: Indirection2[str] reveal_type(z) # N: Revealed type is "builtins.int" Indirection3 = FlexibleAlias[Tuple[T, U], AnInt[T]] w: Indirection3[str, int] reveal_type(w) # N: Revealed type is "builtins.int" [builtins fixtures/dict.pyi] [case testFlexibleAlias2] # flags: --always-true=BOGUS from typing import TypeVar, Any from mypy_extensions import FlexibleAlias T = TypeVar('T') BOGUS = True if BOGUS: Bogus = FlexibleAlias[T, Any] else: Bogus = FlexibleAlias[T, T] class A: x: Bogus[str] reveal_type(A().x) # N: Revealed type is "Any" def foo(x: Bogus[int]) -> None: reveal_type(x) # N: Revealed type is "Any" [builtins fixtures/dict.pyi] [case testFlexibleAlias3] # flags: --always-false=BOGUS from typing import TypeVar, Any from mypy_extensions import FlexibleAlias T = TypeVar('T') BOGUS = True if BOGUS: Bogus = FlexibleAlias[T, Any] else: Bogus = FlexibleAlias[T, T] class A: x: Bogus[str] reveal_type(A().x) # N: Revealed type is "builtins.str" def foo(x: Bogus[int]) -> None: reveal_type(x) # N: Revealed type is "builtins.int" [builtins fixtures/dict.pyi] [case testOverrideByIdemAliasCorrectType] C = C class C: # type: ignore pass x: C reveal_type(x) # N: Revealed type is "__main__.C" [out] [case testOverrideByIdemAliasCorrectTypeReversed] class C: pass C = C # type: ignore x: C reveal_type(x) # N: Revealed type is "__main__.C" [out] [case testOverrideByIdemAliasCorrectTypeImported] from other import C as B C = B x: C reveal_type(x) # N: Revealed type is "other.C" [file other.py] class C: pass [out] [case testConditionalExceptionAlias] try: E = E except BaseException: class E(BaseException): pass # type: ignore try: pass except E as e: reveal_type(e) # N: Revealed type is "__main__.E" [builtins fixtures/exception.pyi] [out] [case testNestedClassOnAliasAsType] class Out: class In: class Inner: pass O = Out I = Out.In OI = O.In A = Out B = A w: O.In x: I.Inner y: OI.Inner z: B.In reveal_type(w) # N: Revealed type is "__main__.Out.In" reveal_type(x) # N: Revealed type is "__main__.Out.In.Inner" reveal_type(y) # N: Revealed type is "__main__.Out.In.Inner" reveal_type(z) # N: Revealed type is "__main__.Out.In" [case testSimplePep613] from typing_extensions import TypeAlias x: TypeAlias = str a: x reveal_type(a) # N: Revealed type is "builtins.str" y: TypeAlias = "str" b: y reveal_type(b) # N: Revealed type is "builtins.str" z: TypeAlias = "int | str" c: z reveal_type(c) # N: Revealed type is "builtins.int | builtins.str" [builtins fixtures/tuple.pyi] [case testForwardRefPep613] from typing_extensions import TypeAlias x: TypeAlias = "MyClass" a: x reveal_type(a) # N: Revealed type is "__main__.MyClass" class MyClass: ... [builtins fixtures/tuple.pyi] [case testInvalidPep613] from typing_extensions import TypeAlias x: TypeAlias = list(int) # E: Invalid type alias: expression is not a valid type \ # E: Too many arguments for "list" a: x [builtins fixtures/tuple.pyi] [case testAliasedImportPep613] import typing as tpp import typing_extensions as tpx from typing import TypeAlias as TPA from typing_extensions import TypeAlias as TXA import typing import typing_extensions Int1: tpp.TypeAlias = int Int2: tpx.TypeAlias = int Int3: TPA = int Int4: TXA = int Int5: typing.TypeAlias = int Int6: typing_extensions.TypeAlias = int x1: Int1 = "str" # E: Incompatible types in assignment (expression has type "str", variable has type "int") x2: Int2 = "str" # E: Incompatible types in assignment (expression has type "str", variable has type "int") x3: Int3 = "str" # E: Incompatible types in assignment (expression has type "str", variable has type "int") x4: Int4 = "str" # E: Incompatible types in assignment (expression has type "str", variable has type "int") x5: Int5 = "str" # E: Incompatible types in assignment (expression has type "str", variable has type "int") x6: Int6 = "str" # E: Incompatible types in assignment (expression has type "str", variable has type "int") [builtins fixtures/tuple.pyi] [typing fixtures/typing-medium.pyi] [case testFunctionScopePep613] from typing_extensions import TypeAlias def f() -> None: x: TypeAlias = str a: x reveal_type(a) # N: Revealed type is "builtins.str" y: TypeAlias = "str" b: y reveal_type(b) # N: Revealed type is "builtins.str" [builtins fixtures/tuple.pyi] [case testImportCyclePep613] # cmd: mypy -m t t2 [file t.py] MYPY = False if MYPY: from t2 import A x: A reveal_type(x) # N: Revealed type is "builtins.str" [file t2.py] from typing_extensions import TypeAlias A: TypeAlias = str [builtins fixtures/bool.pyi] [out] [case testLiteralStringPep675] # flags: --python-version 3.11 from typing import LiteralString as tpLS from typing_extensions import LiteralString as tpxLS def f(a: tpLS, b: tpxLS) -> None: reveal_type(a) # N: Revealed type is "builtins.str" reveal_type(b) # N: Revealed type is "builtins.str" # This isn't the correct behaviour, but should unblock use of LiteralString in typeshed f("asdf", "asdf") string: str f(string, string) [builtins fixtures/tuple.pyi] [typing fixtures/typing-medium.pyi] [case testForwardTypeVarRefWithRecursiveFlag] import c [file a.py] from typing import TypeVar, List, Any, Generic from b import Alias T = TypeVar("T", bound=Alias[Any]) def foo(x: T) -> T: ... [file b.py] from c import C from typing import TypeVar, List S = TypeVar("S") Alias = List[C[S]] [file c.py] from typing import TypeVar, List, Generic import a S = TypeVar("S") class C(Generic[S], List[Defer]): ... class Defer: ... [builtins fixtures/list.pyi] [case testClassLevelTypeAliasesInUnusualContexts] from typing import Union from typing_extensions import TypeAlias class Foo: pass NormalImplicit = Foo NormalExplicit: TypeAlias = Foo SpecialImplicit = Union[int, str] SpecialExplicit: TypeAlias = Union[int, str] class Parent: NormalImplicit = Foo NormalExplicit: TypeAlias = Foo SpecialImplicit = Union[int, str] SpecialExplicit: TypeAlias = Union[int, str] class Child(Parent): pass p = Parent() c = Child() # Use type aliases in a runtime context reveal_type(NormalImplicit) # N: Revealed type is "def () -> __main__.Foo" reveal_type(NormalExplicit) # N: Revealed type is "def () -> __main__.Foo" reveal_type(SpecialImplicit) # N: Revealed type is "typing._SpecialForm" reveal_type(SpecialExplicit) # N: Revealed type is "typing._SpecialForm" reveal_type(Parent.NormalImplicit) # N: Revealed type is "def () -> __main__.Foo" reveal_type(Parent.NormalExplicit) # N: Revealed type is "def () -> __main__.Foo" reveal_type(Parent.SpecialImplicit) # N: Revealed type is "typing._SpecialForm" reveal_type(Parent.SpecialExplicit) # N: Revealed type is "typing._SpecialForm" reveal_type(Child.NormalImplicit) # N: Revealed type is "def () -> __main__.Foo" reveal_type(Child.NormalExplicit) # N: Revealed type is "def () -> __main__.Foo" reveal_type(Child.SpecialImplicit) # N: Revealed type is "typing._SpecialForm" reveal_type(Child.SpecialExplicit) # N: Revealed type is "typing._SpecialForm" reveal_type(p.NormalImplicit) # N: Revealed type is "def () -> __main__.Foo" reveal_type(p.NormalExplicit) # N: Revealed type is "def () -> __main__.Foo" reveal_type(p.SpecialImplicit) # N: Revealed type is "typing._SpecialForm" reveal_type(p.SpecialExplicit) # N: Revealed type is "typing._SpecialForm" reveal_type(c.NormalImplicit) # N: Revealed type is "def () -> __main__.Foo" reveal_type(p.NormalExplicit) # N: Revealed type is "def () -> __main__.Foo" reveal_type(c.SpecialImplicit) # N: Revealed type is "typing._SpecialForm" reveal_type(c.SpecialExplicit) # N: Revealed type is "typing._SpecialForm" # Use type aliases in a type alias context in a plausible way def plausible_top_1() -> NormalImplicit: pass def plausible_top_2() -> NormalExplicit: pass def plausible_top_3() -> SpecialImplicit: pass def plausible_top_4() -> SpecialExplicit: pass reveal_type(plausible_top_1) # N: Revealed type is "def () -> __main__.Foo" reveal_type(plausible_top_2) # N: Revealed type is "def () -> __main__.Foo" reveal_type(plausible_top_3) # N: Revealed type is "def () -> builtins.int | builtins.str" reveal_type(plausible_top_4) # N: Revealed type is "def () -> builtins.int | builtins.str" def plausible_parent_1() -> Parent.NormalImplicit: pass # E: Variable "__main__.Parent.NormalImplicit" is not valid as a type \ # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases def plausible_parent_2() -> Parent.NormalExplicit: pass def plausible_parent_3() -> Parent.SpecialImplicit: pass def plausible_parent_4() -> Parent.SpecialExplicit: pass reveal_type(plausible_parent_1) # N: Revealed type is "def () -> Parent.NormalImplicit?" reveal_type(plausible_parent_2) # N: Revealed type is "def () -> __main__.Foo" reveal_type(plausible_parent_3) # N: Revealed type is "def () -> builtins.int | builtins.str" reveal_type(plausible_parent_4) # N: Revealed type is "def () -> builtins.int | builtins.str" def plausible_child_1() -> Child.NormalImplicit: pass # E: Variable "__main__.Parent.NormalImplicit" is not valid as a type \ # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases def plausible_child_2() -> Child.NormalExplicit: pass def plausible_child_3() -> Child.SpecialImplicit: pass def plausible_child_4() -> Child.SpecialExplicit: pass reveal_type(plausible_child_1) # N: Revealed type is "def () -> Child.NormalImplicit?" reveal_type(plausible_child_2) # N: Revealed type is "def () -> __main__.Foo" reveal_type(plausible_child_3) # N: Revealed type is "def () -> builtins.int | builtins.str" reveal_type(plausible_child_4) # N: Revealed type is "def () -> builtins.int | builtins.str" # Use type aliases in a type alias context in an implausible way def weird_parent_1() -> p.NormalImplicit: pass # E: Name "p.NormalImplicit" is not defined def weird_parent_2() -> p.NormalExplicit: pass # E: Name "p.NormalExplicit" is not defined def weird_parent_3() -> p.SpecialImplicit: pass # E: Name "p.SpecialImplicit" is not defined def weird_parent_4() -> p.SpecialExplicit: pass # E: Name "p.SpecialExplicit" is not defined reveal_type(weird_parent_1) # N: Revealed type is "def () -> Any" reveal_type(weird_parent_2) # N: Revealed type is "def () -> Any" reveal_type(weird_parent_3) # N: Revealed type is "def () -> Any" reveal_type(weird_parent_4) # N: Revealed type is "def () -> Any" def weird_child_1() -> c.NormalImplicit: pass # E: Name "c.NormalImplicit" is not defined def weird_child_2() -> c.NormalExplicit: pass # E: Name "c.NormalExplicit" is not defined def weird_child_3() -> c.SpecialImplicit: pass # E: Name "c.SpecialImplicit" is not defined def weird_child_4() -> c.SpecialExplicit: pass # E: Name "c.SpecialExplicit" is not defined reveal_type(weird_child_1) # N: Revealed type is "def () -> Any" reveal_type(weird_child_2) # N: Revealed type is "def () -> Any" reveal_type(weird_child_3) # N: Revealed type is "def () -> Any" reveal_type(weird_child_4) # N: Revealed type is "def () -> Any" [builtins fixtures/tuple.pyi] [typing fixtures/typing-medium.pyi] [case testMalformedTypeAliasRuntimeReassignments] from typing import Union from typing_extensions import TypeAlias class Foo: pass NormalImplicit = Foo NormalExplicit: TypeAlias = Foo SpecialImplicit = Union[int, str] SpecialExplicit: TypeAlias = Union[int, str] class Parent: NormalImplicit = Foo NormalExplicit: TypeAlias = Foo SpecialImplicit = Union[int, str] SpecialExplicit: TypeAlias = Union[int, str] class Child(Parent): pass p = Parent() c = Child() NormalImplicit = 4 # E: Cannot assign multiple types to name "NormalImplicit" without an explicit "type[...]" annotation \ # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]") NormalExplicit = 4 # E: Cannot assign multiple types to name "NormalExplicit" without an explicit "type[...]" annotation \ # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]") SpecialImplicit = 4 # E: Cannot assign multiple types to name "SpecialImplicit" without an explicit "type[...]" annotation SpecialExplicit = 4 # E: Cannot assign multiple types to name "SpecialExplicit" without an explicit "type[...]" annotation Parent.NormalImplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]") Parent.NormalExplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]") Parent.SpecialImplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "") Parent.SpecialExplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "") Child.NormalImplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]") Child.NormalExplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]") Child.SpecialImplicit = 4 Child.SpecialExplicit = 4 p.NormalImplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]") p.NormalExplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]") p.SpecialImplicit = 4 p.SpecialExplicit = 4 c.NormalImplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]") c.NormalExplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]") c.SpecialImplicit = 4 c.SpecialExplicit = 4 [builtins fixtures/tuple.pyi] [typing fixtures/typing-medium.pyi] [case testNewStyleUnionInTypeAliasWithMalformedInstance] from typing import List A = List[int, str] | int # E: "list" expects 1 type argument, but 2 given B = int | list[int, str] # E: "list" expects 1 type argument, but 2 given a: A b: B reveal_type(a) # N: Revealed type is "builtins.list[Any] | builtins.int" reveal_type(b) # N: Revealed type is "builtins.int | builtins.list[Any]" [builtins fixtures/type.pyi] [case testValidTypeAliasValues] from typing import TypeVar, Generic, List T = TypeVar("T", int, str) S = TypeVar("S", int, bytes) class C(Generic[T]): ... class D(C[S]): ... # E: Invalid type argument value for "C" U = TypeVar("U") A = List[C[U]] x: A[bytes] # E: Value of type variable "T" of "C" cannot be "bytes" V = TypeVar("V", bound=int) class E(Generic[V]): ... B = List[E[U]] y: B[str] # E: Type argument "str" of "E" must be a subtype of "int" [case testValidTypeAliasValuesMoreRestrictive] from typing import TypeVar, Generic, List T = TypeVar("T") S = TypeVar("S", int, str) U = TypeVar("U", bound=int) class C(Generic[T]): ... A = List[C[S]] x: A[int] x_bad: A[bytes] # E: Value of type variable "S" of "A" cannot be "bytes" B = List[C[U]] y: B[int] y_bad: B[str] # E: Type argument "str" of "B" must be a subtype of "int" [case testTupleWithDifferentArgs] Alias1 = tuple[float] Alias2 = tuple[float, float] Alias3 = tuple[float, ...] Alias4 = tuple[float, float, ...] # E: Unexpected "..." [builtins fixtures/tuple.pyi] [case testTupleWithDifferentArgsStub] # https://github.com/python/mypy/issues/11098 import tup [file tup.pyi] Correct1 = str | tuple[float, float, str] Correct2 = tuple[float] | str Correct3 = tuple[float, ...] | str Correct4 = tuple[float, str] | str Correct5 = tuple[int, str] Correct6 = tuple[int, ...] RHSAlias1: type = tuple[int, int] RHSAlias2: type = tuple[int] RHSAlias3: type = tuple[int, ...] # Wrong: WrongTypeElement = str | tuple[float, 1] # E: Invalid type: try using Literal[1] instead? WrongEllipsis = str | tuple[float, float, ...] # E: Unexpected "..." [builtins fixtures/tuple.pyi] [case testCompiledNoCrashOnSingleItemUnion] # flags: --no-strict-optional from typing import Callable, Union, Generic, TypeVar Alias = Callable[[], int] T = TypeVar("T") class C(Generic[T]): attr: Union[Alias, None] = None @classmethod def test(cls) -> None: cls.attr [builtins fixtures/classmethod.pyi] [case testRecursiveAliasTuple] from typing_extensions import TypeAlias from typing import Literal, Tuple, Union Expr: TypeAlias = Union[ Tuple[Literal[123], int], Tuple[Literal[456], "Expr"], ] def eval(e: Expr) -> int: if e[0] == 123: return e[1] elif e[0] == 456: return -eval(e[1]) [builtins fixtures/dict-full.pyi] [case testTypeAliasType] from typing import Union from typing_extensions import TypeAliasType TestType = TypeAliasType("TestType", Union[int, str]) x: TestType = 42 y: TestType = 'a' z: TestType = object() # E: Incompatible types in assignment (expression has type "object", variable has type "int | str") TA = TypeAliasType("TA", value=int) a: TA = 1 b: TA = 's' # E: Incompatible types in assignment (expression has type "str", variable has type "int") TA2 = TypeAliasType("TA2", type_params=(), value=int) # shuffled arguments a2: TA2 = 1 b2: TA2 = 's' # E: Incompatible types in assignment (expression has type "str", variable has type "int") reveal_type(TestType) # N: Revealed type is "typing_extensions.TypeAliasType" TestType() # E: "TypeAliasType" not callable class A: ClassAlias = TypeAliasType("ClassAlias", int) xc: A.ClassAlias = 1 yc: A.ClassAlias = "" # E: Incompatible types in assignment (expression has type "str", variable has type "int") [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 TestType = TypeAliasType("T", int) # E: String argument 1 "T" to TypeAliasType(...) does not match variable name "TestType" T1 = T2 = TypeAliasType("T", int) t1: T1 # E: Variable "__main__.T1" is not valid as a type \ # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases T3 = TypeAliasType("T3", -1) # E: Invalid type: try using Literal[-1] instead? t3: T3 reveal_type(t3) # N: Revealed type is "Any" T4 = TypeAliasType("T4") # E: Missing positional argument "value" in call to "TypeAliasType" T5 = TypeAliasType("T5", int, str) # E: Too many positional arguments for "TypeAliasType" \ # N: "TypeAliasType" defined in "typing_extensions" \ # E: Argument 3 to "TypeAliasType" has incompatible type "type[str]"; expected "tuple[TypeVar? | ParamSpec? | TypeVarTuple?, ...]" [builtins fixtures/tuple.pyi] [typing fixtures/typing-full.pyi] [case testTypeAliasTypeGeneric] from typing import Callable, Dict, Generic, TypeVar, Tuple from typing_extensions import TypeAliasType, TypeVarTuple, ParamSpec, Unpack K = TypeVar('K') V = TypeVar('V') T = TypeVar('T') Ts = TypeVarTuple("Ts") Ts1 = TypeVarTuple("Ts1") P = ParamSpec("P") TestType = TypeAliasType("TestType", Dict[K, V], type_params=(K, V)) x: TestType[int, str] = {1: 'a'} y: TestType[str, int] = {'a': 1} z: TestType[str, int] = {1: 'a'} # E: Dict entry 0 has incompatible type "int": "str"; expected "str": "int" w: TestType[int] # E: Bad number of arguments for type alias, expected 2, given 1 InvertedDict = TypeAliasType("InvertedDict", Dict[K, V], type_params=(V, K)) xi: InvertedDict[str, int] = {1: 'a'} yi: InvertedDict[str, int] = {'a': 1} # E: Dict entry 0 has incompatible type "str": "int"; expected "int": "str" zi: InvertedDict[int, str] = {1: 'a'} # E: Dict entry 0 has incompatible type "int": "str"; expected "str": "int" reveal_type(xi) # N: Revealed type is "builtins.dict[builtins.int, builtins.str]" VariadicAlias1 = TypeAliasType("VariadicAlias1", Tuple[Unpack[Ts]], type_params=(Ts,)) VariadicAlias2 = TypeAliasType("VariadicAlias2", Tuple[Unpack[Ts], K], type_params=(Ts, K)) VariadicAlias3 = TypeAliasType("VariadicAlias3", Callable[[Unpack[Ts]], int], type_params=(Ts,)) xv: VariadicAlias1[int, str] = (1, 'a') yv: VariadicAlias1[str, int] = (1, 'a') # E: Incompatible types in assignment (expression has type "tuple[int, str]", variable has type "tuple[str, int]") zv: VariadicAlias2[int, str] = (1, 'a') def int_in_int_out(x: int) -> int: return x wv: VariadicAlias3[int] = int_in_int_out reveal_type(wv) # N: Revealed type is "def (builtins.int) -> builtins.int" ParamAlias = TypeAliasType("ParamAlias", Callable[P, int], type_params=(P,)) def f(x: str, y: float) -> int: return 1 def g(x: int, y: float) -> int: return 1 xp1: ParamAlias[str, float] = f xp2: ParamAlias[str, float] = g # E: Incompatible types in assignment (expression has type "Callable[[int, float], int]", variable has type "Callable[[str, float], int]") xp3: ParamAlias[str, float] = lambda x, y: 1 class G(Generic[P, T]): ... ParamAlias2 = TypeAliasType("ParamAlias2", G[P, T], type_params=(P, T)) xp: ParamAlias2[[int], str] reveal_type(xp) # N: Revealed type is "__main__.G[[builtins.int], builtins.str]" [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testTypeAliasTypeInvalidGeneric_no_native_parse] from typing_extensions import TypeAliasType, TypeVarTuple, ParamSpec from typing import Callable, Dict, Generic, TypeVar, Tuple, Unpack K = TypeVar('K') V = TypeVar('V') T = TypeVar('T') Ts = TypeVarTuple("Ts") Ts1 = TypeVarTuple("Ts1") P = ParamSpec("P") Ta0 = TypeAliasType("Ta0", int, type_params=(T, T)) # E: Duplicate type variable "T" in type_params argument to TypeAliasType Ta1 = TypeAliasType("Ta1", int, type_params=K) # E: Tuple literal expected as the type_params argument to TypeAliasType Ta2 = TypeAliasType("Ta2", int, type_params=(None,)) # E: Free type variable expected in type_params argument to TypeAliasType Ta3 = TypeAliasType("Ta3", Dict[K, V], type_params=(V,)) # E: Type variable "K" is not included in type_params partially_generic1: Ta3[int] = {"a": 1} reveal_type(partially_generic1) # N: Revealed type is "builtins.dict[Any, builtins.int]" partially_generic2: Ta3[int] = {1: "a"} # E: Dict entry 0 has incompatible type "int": "str"; expected "Any": "int" Ta4 = TypeAliasType("Ta4", Tuple[Unpack[Ts]], type_params=(Ts, Ts1)) # E: Can only use one TypeVarTuple in type_params argument to TypeAliasType Ta5 = TypeAliasType("Ta5", Dict) # Unlike old style aliases, this is not generic non_generic_dict: Ta5[int, str] # E: Bad number of arguments for type alias, expected 0, given 2 reveal_type(non_generic_dict) # N: Revealed type is "builtins.dict[Any, Any]" Ta6 = TypeAliasType("Ta6", Tuple[Unpack[Ts]]) # E: TypeVarTuple "Ts" is not included in type_params unbound_tvt_alias: Ta6[int] # E: Bad number of arguments for type alias, expected 0, given 1 reveal_type(unbound_tvt_alias) # N: Revealed type is "builtins.tuple[Any, ...]" class G(Generic[P, T]): ... Ta7 = TypeAliasType("Ta7", G[P, T]) # E: ParamSpec "P" is not included in type_params \ # E: Type variable "T" is not included in type_params unbound_ps_alias: Ta7[[int], str] # E: Bracketed expression "[...]" is not valid as a type \ # N: Did you mean "List[...]"? \ # E: Bad number of arguments for type alias, expected 0, given 2 reveal_type(unbound_ps_alias) # N: Revealed type is "__main__.G[Any, Any]" Ta8 = TypeAliasType("Ta8", Callable[P, int]) # E: ParamSpec "P" is not included in type_params unbound_ps_alias2: Ta8[int] # E: Bad number of arguments for type alias, expected 0, given 1 reveal_type(unbound_ps_alias2) # N: Revealed type is "def [P] (*Any, **Any) -> builtins.int" Ta9 = TypeAliasType("Ta9", Callable[P, T]) # E: ParamSpec "P" is not included in type_params \ # E: Type variable "T" is not included in type_params unbound_ps_alias3: Ta9[int, str] # E: Bad number of arguments for type alias, expected 0, given 2 reveal_type(unbound_ps_alias3) # N: Revealed type is "def [P] (*Any, **Any) -> Any" Ta10 = TypeAliasType("Ta10", Callable[[Unpack[Ts]], str]) # E: TypeVarTuple "Ts" is not included in type_params unbound_tvt_alias2: Ta10[int] # E: Bad number of arguments for type alias, expected 0, given 1 reveal_type(unbound_tvt_alias2) # N: Revealed type is "def (*Any) -> builtins.str" class A(Generic[T]): Ta11 = TypeAliasType("Ta11", Dict[str, T], type_params=(T,)) # E: Can't use bound type variable "T" to define generic alias x: A.Ta11 = {"a": 1} reveal_type(x) # N: Revealed type is "builtins.dict[builtins.str, Any]" [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testTypeAliasTypeNoUnpackInTypeParams311] # flags: --python-version 3.11 from typing_extensions import TypeAliasType, TypeVar, TypeVarTuple, Unpack T = TypeVar("T") Ts = TypeVarTuple("Ts") Ta1 = TypeAliasType("Ta1", None, type_params=(*Ts,)) # E: can't use starred expression here Ta2 = TypeAliasType("Ta2", None, type_params=(Unpack[Ts],)) # E: Free type variable expected in type_params argument to TypeAliasType \ # N: Don't Unpack type variables in type_params [builtins fixtures/tuple.pyi] [case testAliasInstanceNameClash] from lib import func class A: ... func(A()) # E: Argument 1 to "func" has incompatible type "__main__.A"; expected "lib.A" [file lib.py] from typing import List, Union A = Union[int, List[A]] def func(x: A) -> int: ... [builtins fixtures/tuple.pyi] [case testAliasNonGeneric] from typing_extensions import TypeAlias class Foo: ... ImplicitFoo = Foo ExplicitFoo: TypeAlias = Foo x1: ImplicitFoo[str] # E: "Foo" expects no type arguments, but 1 given x2: ExplicitFoo[str] # E: "Foo" expects no type arguments, but 1 given def is_foo(x: object): if isinstance(x, ImplicitFoo): pass if isinstance(x, ExplicitFoo): pass [builtins fixtures/tuple.pyi] [case testAliasExplicitNoArgsTuple] from typing import Any, Tuple, assert_type from typing_extensions import TypeAlias Implicit = Tuple Explicit: TypeAlias = Tuple x1: Implicit[str] # E: Bad number of arguments for type alias, expected 0, given 1 x2: Explicit[str] # E: Bad number of arguments for type alias, expected 0, given 1 assert_type(x1, Tuple[Any, ...]) assert_type(x2, Tuple[Any, ...]) [builtins fixtures/tuple.pyi] [case testAliasExplicitNoArgsCallable] from typing import Any, Callable, assert_type from typing_extensions import TypeAlias Implicit = Callable Explicit: TypeAlias = Callable x1: Implicit[str] # E: Bad number of arguments for type alias, expected 0, given 1 x2: Explicit[str] # E: Bad number of arguments for type alias, expected 0, given 1 assert_type(x1, Callable[..., Any]) assert_type(x2, Callable[..., Any]) [builtins fixtures/tuple.pyi] [case testExplicitTypeAliasToSameNameOuterProhibited] from typing import TypeVar, Generic from typing_extensions import TypeAlias T = TypeVar("T") class Foo(Generic[T]): bar: Bar[T] class Bar(Generic[T]): Foo: TypeAlias = Foo[T] # E: Can't use bound type variable "T" to define generic alias [builtins fixtures/tuple.pyi] [case testExplicitTypeAliasToSameNameOuterAllowed] from typing import TypeVar, Generic from typing_extensions import TypeAlias T = TypeVar("T") class Foo(Generic[T]): bar: Bar[T] U = TypeVar("U") class Bar(Generic[T]): Foo: TypeAlias = Foo[U] var: Foo[T] x: Bar[int] reveal_type(x.var.bar) # N: Revealed type is "__main__.Bar[builtins.int]" [builtins fixtures/tuple.pyi] [case testExplicitTypeAliasClassVarProhibited] from typing import ClassVar from typing_extensions import TypeAlias Foo: TypeAlias = ClassVar[int] # E: ClassVar[...] can't be used inside a type alias [builtins fixtures/tuple.pyi] [case testAnnotatedWithCallableAsParameterTypeAlias] from typing_extensions import Annotated, TypeAlias def something() -> None: ... A: TypeAlias = list[Annotated[str, something()]] a: A reveal_type(a) # N: Revealed type is "builtins.list[builtins.str]" [builtins fixtures/tuple.pyi] [case testAnnotatedWithCallableAsParameterTypeAliasDeeper] from typing_extensions import Annotated, TypeAlias def something() -> None: ... A: TypeAlias = list[Annotated[Annotated[str, something()], something()]] a: A reveal_type(a) # N: Revealed type is "builtins.list[builtins.str]" [builtins fixtures/tuple.pyi] [case testTypeAliasDict] D = dict[str, int] d = D() reveal_type(d) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]" reveal_type(D()) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]" reveal_type(D(x=1)) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]" reveal_type(D(x="asdf")) # E: No overload variant of "dict" matches argument type "str" \ # N: Possible overload variants: \ # N: def dict(**kwargs: int) -> dict[str, int] \ # N: def dict(arg: Iterable[tuple[str, int]], **kwargs: int) -> dict[str, int] \ # N: Revealed type is "Any" [builtins fixtures/dict.pyi] [case testTypeAliasesInCyclicImport1] import p.aliases [file p/__init__.py] [file p/aliases.py] from typing_extensions import TypeAlias from .defs import C, Alias1 Alias2: TypeAlias = Alias1[C] [file p/defs.py] from typing import TypeVar from typing_extensions import TypeAlias import p.aliases C = TypeVar("C", bound="SomeClass") Alias1: TypeAlias = C class SomeClass: pass [builtins fixtures/tuple.pyi] [typing fixtures/typing-full.pyi] [case testTypeAliasesInCyclicImport2] import p.aliases [file p/__init__.py] [file p/aliases.py] from typing_extensions import TypeAlias from .defs import C, Alias1 Alias2: TypeAlias = Alias1[C] [file p/defs.py] from typing import TypeVar, Union from typing_extensions import TypeAlias import p.aliases C = TypeVar("C", bound="SomeClass") Alias1: TypeAlias = Union[C, int] class SomeClass: pass [builtins fixtures/tuple.pyi] [case testTypeAliasesInCyclicImport3] import p.aliases [file p/__init__.py] [file p/aliases.py] from typing_extensions import TypeAlias from .defs import C, Alias1 Alias2: TypeAlias = Alias1[C] [file p/defs.py] from typing import TypeVar from typing_extensions import TypeAlias import p.aliases C = TypeVar("C", bound="list[SomeClass]") Alias1: TypeAlias = C class SomeClass: pass [builtins fixtures/tuple.pyi] [typing fixtures/typing-full.pyi] [case testTypeAliasesInCyclicImport4] import p.aliases [file p/__init__.py] [file p/aliases.py] from typing_extensions import TypeAlias from .defs import C, Alias1 Alias2: TypeAlias = Alias1[C] [file p/defs.py] from typing import TypeVar, Union from typing_extensions import TypeAlias import p.aliases C = TypeVar("C", bound="list[SomeClass]") Alias1: TypeAlias = Union[C, int] class SomeClass: pass [builtins fixtures/tuple.pyi]