[case testSelfTypeInstance] from typing import TypeVar T = TypeVar('T', bound='A', covariant=True) class A: def copy(self: T) -> T: pass class B(A): pass reveal_type(A().copy) # N: Revealed type is "def () -> __main__.A" reveal_type(B().copy) # N: Revealed type is "def () -> __main__.B" reveal_type(A().copy()) # N: Revealed type is "__main__.A" reveal_type(B().copy()) # N: Revealed type is "__main__.B" [builtins fixtures/bool.pyi] [case testSelfTypeStaticAccess] from typing import TypeVar T = TypeVar('T', bound='A', covariant=True) class A: def copy(self: T) -> T: pass class B(A): pass # Erased instances appear on reveal_type; unrelated to self type def f(a: A) -> None: pass f(A.copy(A())) f(A.copy(B())) f(B.copy(B())) # TODO: make it an error # f(B.copy(A())) def g(a: B) -> None: pass g(A.copy(A())) # E: Argument 1 to "g" has incompatible type "A"; expected "B" g(A.copy(B())) g(B.copy(B())) [builtins fixtures/bool.pyi] [case testSelfTypeReturn] from typing import TypeVar, Type R = TypeVar('R') def _type(self: R) -> Type[R]: pass T = TypeVar('T', bound='A', covariant=True) class A: def copy(self: T) -> T: if B(): return A() # E: Incompatible return value type (got "A", expected "T") elif A(): return B() # E: Incompatible return value type (got "B", expected "T") reveal_type(_type(self)) # N: Revealed type is "type[T`-1]" return reveal_type(_type(self)()) # N: Revealed type is "T`-1" class B(A): pass Q = TypeVar('Q', bound='C', covariant=True) class C: def __init__(self, a: int) -> None: pass def copy(self: Q) -> Q: if self: return reveal_type(_type(self)(1)) # N: Revealed type is "Q`-1" else: return _type(self)() # E: Missing positional argument "a" in call to "C" [builtins fixtures/bool.pyi] [case testSelfTypeClass] from typing import TypeVar, Type T = TypeVar('T', bound='A') class A: @classmethod def new(cls: Type[T]) -> T: return reveal_type(cls()) # N: Revealed type is "T`-1" class B(A): pass Q = TypeVar('Q', bound='C', covariant=True) class C: def __init__(self, a: int) -> None: pass @classmethod def new(cls: Type[Q]) -> Q: if cls: return cls(1) else: return cls() # E: Missing positional argument "a" in call to "C" reveal_type(A.new) # N: Revealed type is "def () -> __main__.A" reveal_type(B.new) # N: Revealed type is "def () -> __main__.B" reveal_type(A.new()) # N: Revealed type is "__main__.A" reveal_type(B.new()) # N: Revealed type is "__main__.B" [builtins fixtures/classmethod.pyi] [case testSelfTypeOverride] from typing import TypeVar, cast T = TypeVar('T', bound='A', covariant=True) class A: def copy(self: T) -> T: pass class B(A): pass Q = TypeVar('Q', bound='C', covariant=True) class C(A): def copy(self: Q) -> Q: pass reveal_type(C().copy) # N: Revealed type is "def () -> __main__.C" reveal_type(C().copy()) # N: Revealed type is "__main__.C" reveal_type(cast(A, C()).copy) # N: Revealed type is "def () -> __main__.A" reveal_type(cast(A, C()).copy()) # N: Revealed type is "__main__.A" [builtins fixtures/bool.pyi] [case testSelfTypeOverrideCompatibility] from typing import overload, TypeVar, Generic T = TypeVar("T") class A(Generic[T]): @overload def f(self: A[int]) -> int: ... @overload def f(self: A[str]) -> str: ... def f(self): ... class B(A[T]): @overload def f(self: A[int]) -> int: ... @overload def f(self: A[str]) -> str: ... def f(self): ... class B2(A[T]): @overload def f(self: A[int]) -> int: ... @overload def f(self: A[str]) -> str: ... @overload def f(self: A[bytes]) -> bytes: ... def f(self): ... class C(A[int]): def f(self) -> int: ... class D(A[str]): def f(self) -> int: ... # E: Return type "int" of "f" incompatible with return type "str" in supertype "A" class E(A[T]): def f(self) -> int: ... # E: Signature of "f" incompatible with supertype "A" \ # N: Superclass: \ # N: @overload \ # N: def f(self) -> int \ # N: @overload \ # N: def f(self) -> str \ # N: Subclass: \ # N: def f(self) -> int class F(A[bytes]): # Note there's an argument to be made that this is actually compatible with the supertype def f(self) -> bytes: ... # E: Signature of "f" incompatible with supertype "A" \ # N: Superclass: \ # N: @overload \ # N: def f(self) -> int \ # N: @overload \ # N: def f(self) -> str \ # N: Subclass: \ # N: def f(self) -> bytes class G(A): def f(self): ... class H(A[int]): def f(self): ... class I(A[int]): def f(*args): ... class J(A[int]): def f(self, arg) -> int: ... # E: Signature of "f" incompatible with supertype "A" \ # N: Superclass: \ # N: def f(self) -> int \ # N: Subclass: \ # N: def f(self, arg: Any) -> int [builtins fixtures/tuple.pyi] [case testSelfTypeOverrideCompatibilityGeneric] from typing import TypeVar, Generic, overload T = TypeVar("T", str, int, None) class A(Generic[T]): @overload def f(self, s: T) -> T: ... @overload def f(self: A[str], s: bytes) -> str: ... def f(self, s: object): ... class B(A[int]): def f(self, s: int) -> int: ... class C(A[None]): def f(self, s: int) -> int: ... # E: Return type "int" of "f" incompatible with return type "None" in supertype "A" \ # E: Argument 1 of "f" is incompatible with supertype "A"; supertype defines the argument type as "None" \ # N: This violates the Liskov substitution principle \ # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides [builtins fixtures/tuple.pyi] [case testSelfTypeOverrideCompatibilityTypeVar] from typing import overload, TypeVar, Union AT = TypeVar("AT", bound="A") class A: @overload def f(self: AT, x: int) -> AT: ... @overload def f(self, x: str) -> None: ... @overload def f(self: AT) -> bytes: ... def f(*a, **kw): ... class B(A): @overload # E: Signature of "f" incompatible with supertype "A" \ # N: Superclass: \ # N: @overload \ # N: def f(self, x: int) -> B \ # N: @overload \ # N: def f(self, x: str) -> None \ # N: @overload \ # N: def f(self) -> bytes \ # N: Subclass: \ # N: @overload \ # N: def f(self, x: int) -> B \ # N: @overload \ # N: def f(self, x: str) -> None def f(self, x: int) -> B: ... @overload def f(self, x: str) -> None: ... def f(*a, **kw): ... [builtins fixtures/dict.pyi] [case testSelfTypeOverrideCompatibilitySelfTypeVar] from typing import Any, Generic, Self, TypeVar, overload T_co = TypeVar('T_co', covariant=True) class Config(Generic[T_co]): @overload def get(self, instance: None) -> Self: ... @overload def get(self, instance: Any) -> T_co: ... def get(self, *a, **kw): ... class MultiConfig(Config[T_co]): @overload def get(self, instance: None) -> Self: ... @overload def get(self, instance: Any) -> T_co: ... def get(self, *a, **kw): ... [builtins fixtures/dict.pyi] [case testSelfTypeSuper] from typing import TypeVar, cast T = TypeVar('T', bound='A', covariant=True) class A: def copy(self: T) -> T: pass Q = TypeVar('Q', bound='B', covariant=True) class B(A): def copy(self: Q) -> Q: reveal_type(self) # N: Revealed type is "Q`-1" reveal_type(super().copy) # N: Revealed type is "def () -> Q`-1" return super().copy() [builtins fixtures/bool.pyi] [case testSelfTypeRecursiveBinding] from typing import TypeVar, Callable, Type T = TypeVar('T', bound='A', covariant=True) class A: # TODO: This is potentially unsafe, as we use T in an argument type def copy(self: T, factory: Callable[[T], T]) -> T: return factory(self) @classmethod def new(cls: Type[T], factory: Callable[[T], T]) -> T: reveal_type(cls) # N: Revealed type is "type[T`-1]" reveal_type(cls()) # N: Revealed type is "T`-1" cls(2) # E: Too many arguments for "A" return cls() class B(A): pass reveal_type(A().copy) # N: Revealed type is "def (factory: def (__main__.A) -> __main__.A) -> __main__.A" reveal_type(B().copy) # N: Revealed type is "def (factory: def (__main__.B) -> __main__.B) -> __main__.B" reveal_type(A.new) # N: Revealed type is "def (factory: def (__main__.A) -> __main__.A) -> __main__.A" reveal_type(B.new) # N: Revealed type is "def (factory: def (__main__.B) -> __main__.B) -> __main__.B" [builtins fixtures/classmethod.pyi] [case testSelfTypeBound] from typing import TypeVar, Callable, cast TA = TypeVar('TA', bound='A', covariant=True) class A: def copy(self: TA) -> TA: pass class C(A): def copy(self: C) -> C: pass class D(A): def copy(self: A) -> A: # E: Return type "A" of "copy" incompatible with return type "D" in supertype "A" pass TB = TypeVar('TB', bound='B', covariant=True) class B(A): x = 1 def copy(self: TB) -> TB: reveal_type(self.x) # N: Revealed type is "builtins.int" return cast(TB, None) [builtins fixtures/bool.pyi] -- # TODO: fail for this -- [case testSelfTypeBare] -- from typing import TypeVar, Type -- -- T = TypeVar('T', bound='E') -- -- class E: -- def copy(self: T, other: T) -> T: pass [case testSelfTypeClone] from typing import TypeVar, Type T = TypeVar('T', bound='C') class C: def copy(self: T) -> T: return self @classmethod def new(cls: Type[T]) -> T: return cls() class D(C): pass reveal_type(D.new) # N: Revealed type is "def () -> __main__.D" reveal_type(D().new) # N: Revealed type is "def () -> __main__.D" reveal_type(D.new()) # N: Revealed type is "__main__.D" reveal_type(D().new()) # N: Revealed type is "__main__.D" Q = TypeVar('Q', bound=C) def clone(arg: Q) -> Q: reveal_type(arg.copy) # N: Revealed type is "def () -> Q`-1" reveal_type(arg.copy()) # N: Revealed type is "Q`-1" reveal_type(arg.new) # N: Revealed type is "def () -> Q`-1" reveal_type(arg.new()) # N: Revealed type is "Q`-1" return arg.copy() def make(cls: Type[Q]) -> Q: reveal_type(cls.new) # N: Revealed type is "def () -> Q`-1" reveal_type(cls().new) # N: Revealed type is "def () -> Q`-1" reveal_type(cls().new()) # N: Revealed type is "Q`-1" return cls.new() [builtins fixtures/classmethod.pyi] [case testSelfTypeGeneric] from typing import TypeVar T = TypeVar('T', int, str) class A: pass class B(A): def __init__(self, arg: T) -> None: super(B, self).__init__() [case testSelfTypeNonsensical] from typing import TypeVar, Type T = TypeVar('T', bound=str) class A: def foo(self: T) -> T: # E: The erased type of self "builtins.str" is not a supertype of its class "__main__.A" return self @classmethod def cfoo(cls: Type[T]) -> T: # E: The erased type of self "type[builtins.str]" is not a supertype of its class "type[__main__.A]" return cls() Q = TypeVar('Q', bound='B') class B: def foo(self: Q) -> Q: return self @classmethod def cfoo(cls: Type[Q]) -> Q: return cls() class C: def foo(self: C) -> C: return self @classmethod def cfoo(cls: Type[C]) -> C: return cls() class D: def foo(self: Q) -> Q: # E: The erased type of self "__main__.B" is not a supertype of its class "__main__.D" return self @staticmethod def bar(self: str) -> str: return self @classmethod def cfoo(cls: Type[Q]) -> Q: # E: The erased type of self "type[__main__.B]" is not a supertype of its class "type[__main__.D]" return cls() [builtins fixtures/classmethod.pyi] [case testSelfTypeLambdaDefault] from typing import Callable class C: @classmethod def foo(cls, arg: Callable[[int], str] = lambda a: '' ) -> None: pass def bar(self, arg: Callable[[int], str] = lambda a: '' ) -> None: pass [builtins fixtures/classmethod.pyi] [case testSelfTypeNew] from typing import TypeVar, Type T = TypeVar('T', bound='A') class A: def __new__(cls: Type[T]) -> T: return cls() def __init_subclass__(cls: Type[T]) -> None: pass class B: def __new__(cls: Type[T]) -> T: # E: The erased type of self "type[__main__.A]" is not a supertype of its class "type[__main__.B]" return cls() def __init_subclass__(cls: Type[T]) -> None: # E: The erased type of self "type[__main__.A]" is not a supertype of its class "type[__main__.B]" pass class C: def __new__(cls: Type[C]) -> C: return cls() def __init_subclass__(cls: Type[C]) -> None: pass class D: def __new__(cls: D) -> D: # E: The erased type of self "__main__.D" is not a supertype of its class "type[__main__.D]" return cls def __init_subclass__(cls: D) -> None: # E: The erased type of self "__main__.D" is not a supertype of its class "type[__main__.D]" pass class E: def __new__(cls) -> E: reveal_type(cls) # N: Revealed type is "type[__main__.E]" return cls() def __init_subclass__(cls) -> None: reveal_type(cls) # N: Revealed type is "type[__main__.E]" [case testSelfTypeNew_explicit] from typing import TypeVar, Type T = TypeVar('T', bound='A') class A: @staticmethod def __new__(cls: Type[T]) -> T: return cls() @classmethod def __init_subclass__(cls: Type[T]) -> None: pass class B: @staticmethod def __new__(cls: Type[T]) -> T: # E: The erased type of self "type[__main__.A]" is not a supertype of its class "type[__main__.B]" return cls() @classmethod def __init_subclass__(cls: Type[T]) -> None: # E: The erased type of self "type[__main__.A]" is not a supertype of its class "type[__main__.B]" pass class C: @staticmethod def __new__(cls: Type[C]) -> C: return cls() @classmethod def __init_subclass__(cls: Type[C]) -> None: pass class D: @staticmethod def __new__(cls: D) -> D: # E: The erased type of self "__main__.D" is not a supertype of its class "type[__main__.D]" return cls @classmethod def __init_subclass__(cls: D) -> None: # E: The erased type of self "__main__.D" is not a supertype of its class "type[__main__.D]" pass class E: @staticmethod def __new__(cls) -> E: reveal_type(cls) # N: Revealed type is "type[__main__.E]" return cls() @classmethod def __init_subclass__(cls) -> None: reveal_type(cls) # N: Revealed type is "type[__main__.E]" [builtins fixtures/classmethod.pyi] [case testSelfTypePropertyUnion] from typing import Union class A: @property def f(self: A) -> int: pass class B: @property def f(self: B) -> int: pass x: Union[A, B] reveal_type(x.f) # N: Revealed type is "builtins.int" [builtins fixtures/property.pyi] [case testSelfTypeProperSupertypeAttribute] from typing import Callable, TypeVar, ClassVar class K: pass T = TypeVar('T', bound=K) class A(K): @property def g(self: K) -> int: return 0 @property def gt(self: T) -> T: return self f: ClassVar[Callable[[object], int]] ft: ClassVar[Callable[[T], T]] class B(A): pass reveal_type(A().g) # N: Revealed type is "builtins.int" reveal_type(A().gt) # N: Revealed type is "__main__.A" reveal_type(A().f()) # N: Revealed type is "builtins.int" reveal_type(A().ft()) # N: Revealed type is "__main__.A" reveal_type(B().g) # N: Revealed type is "builtins.int" reveal_type(B().gt) # N: Revealed type is "__main__.B" reveal_type(B().f()) # N: Revealed type is "builtins.int" reveal_type(B().ft()) # N: Revealed type is "__main__.B" [builtins fixtures/property.pyi] [case testSelfTypeProperSupertypeAttributeTuple] from typing import Callable, TypeVar, Tuple, ClassVar T = TypeVar('T') class A(Tuple[int, int]): @property def g(self: object) -> int: return 0 @property def gt(self: T) -> T: return self f: ClassVar[Callable[[object], int]] ft: ClassVar[Callable[[T], T]] class B(A): pass reveal_type(A().g) # N: Revealed type is "builtins.int" reveal_type(A().gt) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.A]" reveal_type(A().f()) # N: Revealed type is "builtins.int" reveal_type(A().ft()) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.A]" reveal_type(B().g) # N: Revealed type is "builtins.int" reveal_type(B().gt) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.B]" reveal_type(B().f()) # N: Revealed type is "builtins.int" reveal_type(B().ft()) # N: Revealed type is "tuple[builtins.int, builtins.int, fallback=__main__.B]" [builtins fixtures/property.pyi] [case testSelfTypeProperSupertypeAttributeMeta] from typing import Callable, TypeVar, Type, ClassVar T = TypeVar('T') class A(type): @property def g(cls: object) -> int: return 0 @property def gt(cls: T) -> T: return cls f: ClassVar[Callable[[object], int]] ft: ClassVar[Callable[[T], T]] class B(A): pass class X(metaclass=B): def __init__(self, x: int) -> None: pass class Y(X): pass X1: Type[X] reveal_type(X.g) # N: Revealed type is "builtins.int" reveal_type(X.gt) # N: Revealed type is "def (x: builtins.int) -> __main__.X" reveal_type(X.f()) # N: Revealed type is "builtins.int" reveal_type(X.ft()) # N: Revealed type is "def (x: builtins.int) -> __main__.X" reveal_type(Y.g) # N: Revealed type is "builtins.int" reveal_type(Y.gt) # N: Revealed type is "def (x: builtins.int) -> __main__.Y" reveal_type(Y.f()) # N: Revealed type is "builtins.int" reveal_type(Y.ft()) # N: Revealed type is "def (x: builtins.int) -> __main__.Y" reveal_type(X1.g) # N: Revealed type is "builtins.int" reveal_type(X1.gt) # N: Revealed type is "type[__main__.X]" reveal_type(X1.f()) # N: Revealed type is "builtins.int" reveal_type(X1.ft()) # N: Revealed type is "type[__main__.X]" [builtins fixtures/property.pyi] [case testSelfTypeProperSupertypeAttributeGeneric] from typing import Callable, TypeVar, Generic, ClassVar Q = TypeVar('Q', covariant=True) class K(Generic[Q]): q: Q T = TypeVar('T') class A(K[Q]): @property def g(self: K[object]) -> int: return 0 @property def gt(self: K[T]) -> T: return self.q f: ClassVar[Callable[[object], int]] ft: ClassVar[Callable[[T], T]] class B(A[Q]): pass a: A[int] b: B[str] reveal_type(a.g) # N: Revealed type is "builtins.int" reveal_type(a.gt) # N: Revealed type is "builtins.int" reveal_type(a.f()) # N: Revealed type is "builtins.int" reveal_type(a.ft()) # N: Revealed type is "__main__.A[builtins.int]" reveal_type(b.g) # N: Revealed type is "builtins.int" reveal_type(b.gt) # N: Revealed type is "builtins.str" reveal_type(b.f()) # N: Revealed type is "builtins.int" reveal_type(b.ft()) # N: Revealed type is "__main__.B[builtins.str]" [builtins fixtures/property.pyi] [case testSelfTypeRestrictedMethod] from typing import TypeVar, Generic T = TypeVar('T') class C(Generic[T]): def from_item(self: C[str]) -> None: ... i: C[int] s: C[str] i.from_item() # E: Invalid self argument "C[int]" to attribute function "from_item" with type "Callable[[C[str]], None]" s.from_item() [case testSelfTypeRestrictedClassMethod] from typing import TypeVar, Generic, Type T = TypeVar('T') class C(Generic[T]): @classmethod def from_item(cls: Type[C[str]]) -> None: ... class DI(C[int]): ... class DS(C[str]): ... DI().from_item() # E: Invalid self argument "type[DI]" to class attribute function "from_item" with type "Callable[[type[C[str]]], None]" DS().from_item() DI.from_item() # E: Invalid self argument "type[DI]" to attribute function "from_item" with type "Callable[[type[C[str]]], None]" DS.from_item() [builtins fixtures/classmethod.pyi] [case testSelfTypeRestrictedMethodOverload] from typing import TypeVar, Generic, overload, Tuple T = TypeVar('T') class C(Generic[T]): @overload def from_item(self: C[str], item: str) -> None: ... @overload def from_item(self: C[int], item: Tuple[int]) -> None: ... def from_item(self, item): ... ci: C[int] cs: C[str] reveal_type(ci.from_item) # N: Revealed type is "def (item: tuple[builtins.int])" reveal_type(cs.from_item) # N: Revealed type is "def (item: builtins.str)" [builtins fixtures/tuple.pyi] [case testSelfTypeRestrictedMethodOverloadFallback] from typing import TypeVar, Generic, overload, Callable T = TypeVar('T') class C(Generic[T]): @overload def from_item(self: C[str]) -> str: ... @overload def from_item(self, converter: Callable[[T], str]) -> str: ... def from_item(self, converter): ... ci: C[int] cs: C[str] reveal_type(cs.from_item()) # N: Revealed type is "builtins.str" ci.from_item() # E: Missing positional argument "converter" in call to "from_item" of "C" def conv(x: int) -> str: ... def bad(x: str) -> str: ... reveal_type(ci.from_item(conv)) # N: Revealed type is "builtins.str" ci.from_item(bad) # E: Argument 1 to "from_item" of "C" has incompatible type "Callable[[str], str]"; expected "Callable[[int], str]" [case testSelfTypeRestrictedMethodOverloadInit] from typing import TypeVar from lib import P, C reveal_type(P) # N: Revealed type is "Overload(def [T] (use_str: Literal[True]) -> lib.P[builtins.str], def [T] (use_str: Literal[False]) -> lib.P[builtins.int])" reveal_type(P(use_str=True)) # N: Revealed type is "lib.P[builtins.str]" reveal_type(P(use_str=False)) # N: Revealed type is "lib.P[builtins.int]" reveal_type(C) # N: Revealed type is "Overload(def [T] (item: T`1, use_tuple: Literal[False]) -> lib.C[T`1], def [T] (item: T`1, use_tuple: Literal[True]) -> lib.C[builtins.tuple[T`1, ...]])" reveal_type(C(0, use_tuple=False)) # N: Revealed type is "lib.C[builtins.int]" reveal_type(C(0, use_tuple=True)) # N: Revealed type is "lib.C[builtins.tuple[builtins.int, ...]]" T = TypeVar('T') class SubP(P[T]): pass SubP('no') # E: No overload variant of "SubP" matches argument type "str" \ # N: Possible overload variants: \ # N: def [T] SubP(use_str: Literal[True]) -> SubP[T] \ # N: def [T] SubP(use_str: Literal[False]) -> SubP[T] # This is a bit unfortunate: we don't have a way to map the overloaded __init__ to subtype. x = SubP(use_str=True) # E: Need type annotation for "x" reveal_type(x) # N: Revealed type is "__main__.SubP[Any]" y: SubP[str] = SubP(use_str=True) [file lib.pyi] from typing import Literal, TypeVar, Generic, overload, Tuple T = TypeVar('T') class P(Generic[T]): @overload def __init__(self: P[str], use_str: Literal[True]) -> None: ... @overload def __init__(self: P[int], use_str: Literal[False]) -> None: ... class C(Generic[T]): @overload def __init__(self: C[T], item: T, use_tuple: Literal[False]) -> None: ... @overload def __init__(self: C[Tuple[T, ...]], item: T, use_tuple: Literal[True]) -> None: ... [builtins fixtures/bool.pyi] [case testSelfTypeRestrictedMethodOverloadInitFallBacks] from lib import PFallBack, PFallBackAny t: bool xx = PFallBack(t) # E: Need type annotation for "xx" yy = PFallBackAny(t) # OK [file lib.pyi] from typing import Literal, TypeVar, Generic, overload, Tuple, Any class PFallBack(Generic[T]): @overload def __init__(self: PFallBack[str], use_str: Literal[True]) -> None: ... @overload def __init__(self: PFallBack[int], use_str: Literal[False]) -> None: ... @overload def __init__(self, use_str: bool) -> None: ... class PFallBackAny(Generic[T]): @overload def __init__(self: PFallBackAny[str], use_str: Literal[True]) -> None: ... @overload def __init__(self: PFallBackAny[int], use_str: Literal[False]) -> None: ... @overload def __init__(self: PFallBackAny[Any], use_str: bool) -> None: ... [builtins fixtures/bool.pyi] [case testSelfTypeRestrictedMethodOverloadInitBadTypeNoCrash] from lib import P P(0) [file lib.pyi] from typing import overload class P: @overload def __init__(self: Bad, x: int) -> None: ... # E: Name "Bad" is not defined @overload def __init__(self) -> None: ... [case testSelfTypeNarrowBinding] from typing import TypeVar, List, Generic T = TypeVar('T') S = TypeVar('S') class Base(Generic[T]): def get_item(self: Base[List[S]]) -> S: ... class Sub(Base[List[int]]): ... class BadSub(Base[int]): ... reveal_type(Sub().get_item()) # N: Revealed type is "builtins.int" BadSub().get_item() # E: Invalid self argument "BadSub" to attribute function "get_item" with type "Callable[[Base[list[S]]], S]" [builtins fixtures/list.pyi] [case testMixinAllowedWithProtocol] from typing import Protocol, TypeVar class Resource(Protocol): def close(self) -> int: ... class AtomicClose: def atomic_close(self: Resource) -> int: return self.close() T = TypeVar('T', bound=Resource) class Copyable: def copy(self: T) -> T: ... class File(AtomicClose, Copyable): def close(self) -> int: ... class Bad(AtomicClose, Copyable): ... f: File b: Bad f.atomic_close() # OK b.atomic_close() # E: Invalid self argument "Bad" to attribute function "atomic_close" with type "Callable[[Resource], int]" reveal_type(f.copy()) # N: Revealed type is "__main__.File" b.copy() # E: Invalid self argument "Bad" to attribute function "copy" with type "Callable[[T], T]" [builtins fixtures/tuple.pyi] [case testMixinProtocolSuper] from typing import Protocol class Base(Protocol): def func(self) -> int: ... class TweakFunc: def func(self: Base) -> int: return reveal_type(super().func()) # E: Call to abstract method "func" of "Base" with trivial body via super() is unsafe \ # N: Revealed type is "builtins.int" class Good: def func(self) -> int: ... class C(TweakFunc, Good): pass C().func() # OK class Bad: def func(self) -> str: ... class CC(TweakFunc, Bad): pass # E: Definition of "func" in base class "TweakFunc" is incompatible with definition in base class "Bad" [case testBadClassLevelDecoratorHack] from typing import Protocol, TypeVar, Any class FuncLike(Protocol): __call__: Any F = TypeVar('F', bound=FuncLike) class Test: def _deco(func: F) -> F: ... @_deco def meth(self, x: str) -> int: ... reveal_type(Test().meth) # N: Revealed type is "def (x: builtins.str) -> builtins.int" Test()._deco # E: Invalid self argument "Test" to attribute function "_deco" with type "Callable[[F], F]" [builtins fixtures/tuple.pyi] [case testSelfTypeTrickyExample] from typing import * In = TypeVar('In') Out = TypeVar('Out') Mid = TypeVar('Mid') NewOut = TypeVar('NewOut') class Lnk(Generic[In, Out]): def test(self: Lnk[In, Mid], other: Lnk[Mid, NewOut]) -> Lnk[In, NewOut]: ... class X: pass class Y: pass class Z: pass a: Lnk[X, Y] = Lnk() b: Lnk[Y, Z] = Lnk() a.test(b) b.test(a) # E: Argument 1 to "test" of "Lnk" has incompatible type "Lnk[X, Y]"; expected "Lnk[Z, Y]" [case testSelfTypeReallyTrickyExample] from typing import * In = TypeVar('In') Out = TypeVar('Out') Other = TypeVar('Other') _1 = TypeVar('_1') _2 = TypeVar('_2') __1 = TypeVar('__1') __2 = TypeVar('__2') class Lnk(Generic[In, Out]): @overload def __rshift__(self, other: Lnk[Out, Other]) -> Lnk[In,Other]: ... @overload def __rshift__(self: Lnk[In, Tuple[_1, _2]], other: Tuple[Lnk[_1, __1], Lnk[_2, __2]]) -> Lnk[In, Tuple[__1, __2]]: ... def __rshift__(self: Any, other: Any) -> Any: ... a: Lnk[str, Tuple[str, int]] = Lnk() b: Lnk[str, int] = Lnk() c: Lnk[int, float] = Lnk() d: Lnk[str, float] = b >> c # OK e: Lnk[str, Tuple[int, float]] = a >> (b, c) # OK f: Lnk[str, Tuple[float, int]] = a >> (c, b) # E: Unsupported operand types for >> ("Lnk[str, tuple[str, int]]" and "tuple[Lnk[int, float], Lnk[str, int]]") [builtins fixtures/tuple.pyi] [case testSelfTypeMutuallyExclusiveRestrictions] from typing import Generic, TypeVar T = TypeVar('T') class Foo(Generic[T]): def f1(self: Foo[str]) -> None: self.f2() # E: Invalid self argument "Foo[str]" to attribute function "f2" with type "Callable[[Foo[int]], None]" def f2(self: Foo[int]) -> None: self.f1() # E: Invalid self argument "Foo[int]" to attribute function "f1" with type "Callable[[Foo[str]], None]" [case testSelfTypeStructureMetaclassMatch] from typing import TypeVar, Type, Generic, cast Cls = TypeVar('Cls') T = TypeVar('T') class Manager(Generic[Cls]): def create(self: Manager[Type[T]]) -> T: ... class ModelMeta(type): @property def objects(cls: T) -> Manager[T]: ... class Model(metaclass=ModelMeta): pass class Dog(Model): ... class Cat(Model): ... c: Cat = Dog.objects.create() # E: Incompatible types in assignment (expression has type "Dog", variable has type "Cat") d: Dog = Dog.objects.create() [builtins fixtures/property.pyi] [case testSelfTypeProtocolMetaclassMatch] from typing import Type, TypeVar, Protocol class HasX(Protocol): x: int T = TypeVar('T', bound=HasX) class Meta(type): def do_x(cls: Type[T]) -> T: cls.x return cls() class Good(metaclass=Meta): x: int class Bad(metaclass=Meta): pass Good.do_x() Bad.do_x() # E: Invalid self argument "type[Bad]" to attribute function "do_x" with type "Callable[[type[T]], T]" [case testSelfTypeProtocolClassmethodMatch] from typing import Type, TypeVar, Protocol T = TypeVar('T') class HasDoX(Protocol): @classmethod def do_x(cls: Type[T]) -> T: ... class Good: @classmethod def do_x(cls) -> 'Good': ... class Bad: @classmethod def do_x(cls) -> Good: ... good: HasDoX = Good() bad: HasDoX = Bad() [builtins fixtures/classmethod.pyi] [out] main:21: error: Incompatible types in assignment (expression has type "Bad", variable has type "HasDoX") main:21: note: Following member(s) of "Bad" have conflicts: main:21: note: Expected: main:21: note: def do_x(cls) -> Bad main:21: note: Got: main:21: note: def do_x(cls) -> Good [case testSelfTypeNotSelfType] # Friendlier error messages for common mistakes. See #2950 class A: def f(x: int) -> None: ... def g(self: None) -> None: ... [out] main:3: error: "self" parameter missing for a non-static method (or an invalid type for self) main:4: error: The erased type of self "None" is not a supertype of its class "__main__.A" [case testUnionPropertyField] from typing import Union class A: x: int class B: @property def x(self) -> int: return 1 class C: @property def x(self) -> int: return 1 ab: Union[A, B, C] reveal_type(ab.x) # N: Revealed type is "builtins.int" [builtins fixtures/property.pyi] [case testSelfTypeNoTypeVars] from typing import Generic, List, Optional, TypeVar, Any Q = TypeVar("Q") T = TypeVar("T", bound='Super[Any]') class Super(Generic[Q]): @classmethod def meth(cls, arg: List[T]) -> List[T]: pass class Sub(Super[int]): ... def test(x: List[Sub]) -> None: reveal_type(Sub.meth(x)) # N: Revealed type is "builtins.list[__main__.Sub]" [builtins fixtures/isinstancelist.pyi] [case testSelfTypeNoTypeVarsRestrict] from typing import Generic, TypeVar T = TypeVar('T') S = TypeVar('S') class C(Generic[T]): def limited(self: C[str], arg: S) -> S: ... reveal_type(C[str]().limited(0)) # N: Revealed type is "builtins.int" [case testSelfTypeMultipleTypeVars] from typing import Generic, TypeVar, Tuple T = TypeVar('T') S = TypeVar('S') U = TypeVar('U') V = TypeVar('V') class C(Generic[T]): def magic(self: C[Tuple[S, U]]) -> Tuple[T, S, U]: ... class D(Generic[V]): def f(self) -> None: reveal_type(C[Tuple[V, str]]().magic()) # N: Revealed type is "tuple[tuple[V`1, builtins.str], V`1, builtins.str]" [builtins fixtures/tuple.pyi] [case testSelfTypeOnUnion] from typing import TypeVar, Union T = TypeVar('T') class A: same: int class C: def same(self: T) -> T: ... x: Union[A, C] reveal_type(x.same) # N: Revealed type is "builtins.int | (def () -> __main__.C)" [case testSelfTypeOnUnionClassMethod] from typing import TypeVar, Union, Type T = TypeVar('T') class A: same: int class C: @classmethod def same(cls: Type[T]) -> T: ... x: Union[A, C] reveal_type(x.same) # N: Revealed type is "builtins.int | (def () -> __main__.C)" [builtins fixtures/classmethod.pyi] [case SelfTypeOverloadedClassMethod] from lib import Base from typing import overload, Tuple class Sub(Base): @overload @classmethod def make(cls) -> Sub: ... @overload @classmethod def make(cls, num: int) -> Tuple[Sub, ...]: ... @classmethod def make(cls, num=1): ... class Other(Base): ... class Double(Sub): ... reveal_type(Other.make()) # N: Revealed type is "__main__.Other" reveal_type(Other.make(3)) # N: Revealed type is "builtins.tuple[__main__.Other, ...]" reveal_type(Double.make()) # N: Revealed type is "__main__.Sub" reveal_type(Double.make(3)) # N: Revealed type is "builtins.tuple[__main__.Sub, ...]" [file lib.pyi] from typing import overload, TypeVar, Type, Tuple T = TypeVar('T', bound=Base) class Base: @overload @classmethod def make(cls: Type[T]) -> T: ... @overload @classmethod def make(cls: Type[T], num: int) -> Tuple[T, ...]: ... [builtins fixtures/classmethod.pyi] [case testSelfTypeClassMethodOnUnion] from typing import Type, Union, TypeVar T = TypeVar('T') class A: @classmethod def meth(cls: Type[T]) -> T: ... class B(A): ... class C(A): ... t: Type[Union[B, C]] reveal_type(t.meth) # N: Revealed type is "(def () -> __main__.B) | (def () -> __main__.C)" x = t.meth() reveal_type(x) # N: Revealed type is "__main__.B | __main__.C" [builtins fixtures/classmethod.pyi] [case testSelfTypeClassMethodOnUnionGeneric] from typing import Type, Union, TypeVar, Generic T = TypeVar('T') S = TypeVar('S') class A(Generic[T]): @classmethod def meth(cls: Type[S]) -> S: ... t: Type[Union[A[int], A[str]]] x = t.meth() reveal_type(x) # N: Revealed type is "__main__.A[builtins.int] | __main__.A[builtins.str]" [builtins fixtures/classmethod.pyi] [case testSelfTypeClassMethodOnUnionList] from typing import Type, Union, TypeVar, List T = TypeVar('T') class A: @classmethod def meth(cls: Type[T]) -> List[T]: ... class B(A): ... class C(A): ... t: Type[Union[B, C]] x = t.meth()[0] reveal_type(x) # N: Revealed type is "__main__.B | __main__.C" [builtins fixtures/isinstancelist.pyi] [case testSelfTypeClassMethodOverloadedOnInstance] from typing import Optional, Type, TypeVar, overload, Union Id = int A = TypeVar("A", bound='AClass') class AClass: @overload @classmethod def delete(cls: Type[A], id: Id, id2: Id) -> Optional[int]: ... @overload @classmethod def delete(cls: Type[A], id: A, id2: None = None) -> Optional[int]: ... @classmethod def delete(cls: Type[A], id: Union[A, Id], id2: Optional[Id] = None) -> Optional[int]: ... def foo(x: Type[AClass]) -> None: reveal_type(x.delete) # N: Revealed type is "Overload(def (id: builtins.int, id2: builtins.int) -> builtins.int | None, def (id: __main__.AClass, id2: None =) -> builtins.int | None)" y = x() reveal_type(y.delete) # N: Revealed type is "Overload(def (id: builtins.int, id2: builtins.int) -> builtins.int | None, def (id: __main__.AClass, id2: None =) -> builtins.int | None)" y.delete(10, 20) y.delete(y) def bar(x: AClass) -> None: reveal_type(x.delete) # N: Revealed type is "Overload(def (id: builtins.int, id2: builtins.int) -> builtins.int | None, def (id: __main__.AClass, id2: None =) -> builtins.int | None)" x.delete(10, 20) [builtins fixtures/classmethod.pyi] [case testSelfTypeBadTypeIgnoredInConstructor] class Base: ... class Sub(Base): def __init__(self: Base) -> None: ... reveal_type(Sub()) # N: Revealed type is "__main__.Sub" [case testSelfTypeBadTypeIgnoredInConstructorGeneric] from typing import Generic, TypeVar T = TypeVar('T') class Base(Generic[T]): ... class Sub(Base[T]): def __init__(self: Base[T], item: T) -> None: ... reveal_type(Sub(42)) # N: Revealed type is "__main__.Sub[builtins.int]" [case testSelfTypeBadTypeIgnoredInConstructorOverload] from typing import overload class Base: ... class Sub(Base): @overload def __init__(self: Sub, item: int) -> None: ... @overload def __init__(self: Base) -> None: ... def __init__(self, item=None): ... reveal_type(Sub) # N: Revealed type is "Overload(def (item: builtins.int) -> __main__.Sub, def () -> __main__.Sub)" [case testSelfTypeBadTypeIgnoredInConstructorAbstract] from abc import abstractmethod from typing import Protocol class Blah(Protocol): @abstractmethod def something(self) -> None: ... class Concrete(Blah): def __init__(self: Blah) -> None: ... def something(self) -> None: ... Concrete() # OK [case testSelfTypeGenericClassNoClashInstanceMethod] from typing import TypeVar, Generic M = TypeVar("M") T = TypeVar("T") S = TypeVar("S") class Descriptor(Generic[M]): ... class BaseWrapper(Generic[M]): def create_wrapper(self: T, metric_descriptor: Descriptor[M]) -> T: ... class SubWrapper(BaseWrapper[M]): ... def build_wrapper(descriptor: Descriptor[M]) -> BaseWrapper[M]: wrapper: BaseWrapper[M] return wrapper.create_wrapper(descriptor) def build_sub_wrapper(descriptor: Descriptor[S]) -> SubWrapper[S]: wrapper: SubWrapper[S] x = wrapper.create_wrapper(descriptor) reveal_type(x) # N: Revealed type is "__main__.SubWrapper[S`-1]" return x [case testSelfTypeGenericClassNoClashClassMethod] from typing import TypeVar, Generic, Type M = TypeVar("M") T = TypeVar("T") S = TypeVar("S") class Descriptor(Generic[M]): ... class BaseWrapper(Generic[M]): @classmethod def create_wrapper(cls: Type[T], metric_descriptor: Descriptor[M]) -> T: ... class SubWrapper(BaseWrapper[M]): ... def build_wrapper(descriptor: Descriptor[M]) -> BaseWrapper[M]: wrapper_cls: Type[BaseWrapper[M]] return wrapper_cls.create_wrapper(descriptor) def build_sub_wrapper(descriptor: Descriptor[S]) -> SubWrapper[S]: wrapper_cls: Type[SubWrapper[S]] x = wrapper_cls.create_wrapper(descriptor) reveal_type(x) # N: Revealed type is "__main__.SubWrapper[S`-1]" return x [builtins fixtures/classmethod.pyi] [case testSelfTypeGenericClassNoClashClassMethodClassObject] from typing import TypeVar, Generic, Type M = TypeVar("M") T = TypeVar("T") class Descriptor(Generic[M]): ... class BaseWrapper(Generic[M]): @classmethod def create_wrapper(cls: Type[T], metric_descriptor: Descriptor[M]) -> T: ... class SubWrapper(BaseWrapper[M]): ... def build_wrapper(descriptor: Descriptor[M]) -> BaseWrapper[M]: return BaseWrapper.create_wrapper(descriptor) def build_sub_wrapper(descriptor: Descriptor[M]) -> SubWrapper[M]: x = SubWrapper.create_wrapper(descriptor) reveal_type(x) # N: Revealed type is "__main__.SubWrapper[M`-1]" return x def build_wrapper_non_gen(descriptor: Descriptor[int]) -> BaseWrapper[str]: return BaseWrapper.create_wrapper(descriptor) # E: Argument 1 to "create_wrapper" of "BaseWrapper" has incompatible type "Descriptor[int]"; expected "Descriptor[str]" def build_sub_wrapper_non_gen(descriptor: Descriptor[int]) -> SubWrapper[str]: return SubWrapper.create_wrapper(descriptor) # E: Argument 1 to "create_wrapper" of "BaseWrapper" has incompatible type "Descriptor[int]"; expected "Descriptor[str]" [builtins fixtures/classmethod.pyi] [case testSelfTypeInGenericClassUsedFromAnotherGenericClass1] from typing import TypeVar, Generic, Iterator, List, Tuple _T_co = TypeVar("_T_co", covariant=True) _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") S = TypeVar("S") class Z(Iterator[_T_co]): def __new__(cls, __iter1: List[_T1], __iter2: List[_T2]) -> Z[Tuple[_T1, _T2]]: ... def __iter__(self: S) -> S: ... def __next__(self) -> _T_co: ... T = TypeVar('T') class C(Generic[T]): a: List[T] b: List[str] def f(self) -> None: for x, y in Z(self.a, self.b): reveal_type((x, y)) # N: Revealed type is "tuple[T`1, builtins.str]" [builtins fixtures/tuple.pyi] [case testEnumerateReturningSelfFromIter] from typing import Generic, Iterable, Iterator, TypeVar, Tuple T = TypeVar("T") KT = TypeVar("KT") VT = TypeVar("VT") Self = TypeVar("Self") class enumerate(Iterator[Tuple[int, T]], Generic[T]): def __init__(self, iterable: Iterable[T]) -> None: ... def __iter__(self: Self) -> Self: ... def __next__(self) -> Tuple[int, T]: ... class Dict(Generic[KT, VT]): def update(self, __m: Iterable[Tuple[KT, VT]]) -> None: ... class ThingCollection(Generic[T]): collection: Iterable[Tuple[float, T]] index: Dict[int, T] def do_thing(self) -> None: self.index.update((idx, c) for idx, (k, c) in enumerate(self.collection)) [builtins fixtures/tuple.pyi] [case testDequeReturningSelfFromCopy] # Tests a bug with generic self types identified in issue #12641 from typing import Generic, Sequence, TypeVar T = TypeVar("T") Self = TypeVar("Self") class deque(Sequence[T]): def copy(self: Self) -> Self: ... class List(Sequence[T]): ... class Test(Generic[T]): def test(self) -> None: a: deque[List[T]] # previously this failed with 'Incompatible types in assignment (expression has type "deque[List[List[T]]]", variable has type "deque[List[T]]")' b: deque[List[T]] = a.copy() [case testTypingSelfBasic] from typing import Self, List class C: attr: List[Self] def meth(self) -> List[Self]: ... def test(self) -> Self: if bool(): return C() # E: Incompatible return value type (got "C", expected "Self") else: return self class D(C): ... reveal_type(C.meth) # N: Revealed type is "def [Self <: __main__.C] (self: Self`1) -> builtins.list[Self`1]" C.attr # E: Access to generic instance variables via class is ambiguous reveal_type(D().meth()) # N: Revealed type is "builtins.list[__main__.D]" reveal_type(D().attr) # N: Revealed type is "builtins.list[__main__.D]" [case testTypingSelfInvalidLocations] from typing import Self, Callable var: Self # E: Self type is only allowed in annotations within class definition reveal_type(var) # N: Revealed type is "Any" def foo() -> Self: ... # E: Self type is only allowed in annotations within class definition reveal_type(foo) # N: Revealed type is "def () -> Any" bad: Callable[[Self], Self] # E: Self type is only allowed in annotations within class definition reveal_type(bad) # N: Revealed type is "def (Any) -> Any" def func() -> None: var: Self # E: Self type is only allowed in annotations within class definition class C(Self): ... # E: Self type is only allowed in annotations within class definition [case testTypingSelfInvalidArgs] from typing import Self, List class C: x: Self[int] # E: Self type cannot have type arguments def meth(self) -> List[Self[int]]: # E: Self type cannot have type arguments ... [case testTypingSelfConflict] from typing import Self, TypeVar, Tuple T = TypeVar("T") class C: def meth(self: T) -> Tuple[Self, T]: ... # E: Method cannot have explicit self annotation and Self type reveal_type(C().meth()) # N: Revealed type is "tuple[Never, __main__.C]" [builtins fixtures/property.pyi] [case testTypingSelfProperty] from typing import Self, Tuple class C: @property def attr(self) -> Tuple[Self, ...]: ... class D(C): ... reveal_type(D().attr) # N: Revealed type is "builtins.tuple[__main__.D, ...]" [builtins fixtures/property.pyi] [case testTypingSelfCallableVar] from typing import Self, Callable class C: x: Callable[[Self], Self] def meth(self) -> Callable[[Self], Self]: ... class D(C): ... reveal_type(C().x) # N: Revealed type is "def (__main__.C) -> __main__.C" reveal_type(D().x) # N: Revealed type is "def (__main__.D) -> __main__.D" reveal_type(D().meth()) # N: Revealed type is "def (__main__.D) -> __main__.D" [case testTypingSelfClassMethod] from typing import Self class C: @classmethod def meth(cls) -> Self: ... @staticmethod def bad() -> Self: ... # E: Static methods cannot use Self type \ # E: A function returning TypeVar should receive at least one argument containing the same TypeVar \ # N: Consider using the upper bound "C" instead class D(C): ... reveal_type(D.meth()) # N: Revealed type is "__main__.D" reveal_type(D.bad()) # N: Revealed type is "Never" [builtins fixtures/classmethod.pyi] [case testTypingSelfOverload] from typing import Self, overload, Union class C: @overload def foo(self, other: Self) -> Self: ... @overload def foo(self, other: int) -> int: ... def foo(self, other: Union[Self, int]) -> Union[Self, int]: return other class D(C): ... reveal_type(D().foo) # N: Revealed type is "Overload(def (other: __main__.D) -> __main__.D, def (other: builtins.int) -> builtins.int)" [case testTypingSelfNestedInAlias] from typing import Generic, Self, TypeVar, List, Tuple T = TypeVar("T") Pairs = List[Tuple[T, T]] class C(Generic[T]): def pairs(self) -> Pairs[Self]: ... class D(C[T]): ... reveal_type(D[int]().pairs()) # N: Revealed type is "builtins.list[tuple[__main__.D[builtins.int], __main__.D[builtins.int]]]" [builtins fixtures/tuple.pyi] [case testTypingSelfOverrideVar] from typing import Self, TypeVar, Generic T = TypeVar("T") class C(Generic[T]): x: Self class D(C[int]): x: D class Bad(C[int]): x: C[int] # E: Incompatible types in assignment (expression has type "C[int]", base class "C" defined the type as "Bad") [case testTypingSelfOverrideVarMulti] from typing import Self class C: x: Self class D: x: C class E: x: Good class Bad(D, C): # E: Definition of "x" in base class "D" is incompatible with definition in base class "C" ... class Good(E, C): ... [case testTypingSelfAlternativeGenericConstructor] from typing import Self, Generic, TypeVar, Tuple T = TypeVar("T") class C(Generic[T]): def __init__(self, val: T) -> None: ... @classmethod def pair(cls, val: T) -> Tuple[Self, Self]: return (cls(val), C(val)) # E: Incompatible return value type (got "tuple[Self, C[T]]", expected "tuple[Self, Self]") class D(C[int]): pass reveal_type(C.pair(42)) # N: Revealed type is "tuple[__main__.C[builtins.int], __main__.C[builtins.int]]" reveal_type(D.pair("no")) # N: Revealed type is "tuple[__main__.D, __main__.D]" \ # E: Argument 1 to "pair" of "C" has incompatible type "str"; expected "int" [builtins fixtures/classmethod.pyi] [case testTypingSelfMixedTypeVars] from typing import Self, TypeVar, Generic, Tuple T = TypeVar("T") S = TypeVar("S") class C(Generic[T]): def meth(self, arg: S) -> Tuple[Self, S, T]: ... class D(C[int]): ... c: C[int] d: D reveal_type(c.meth("test")) # N: Revealed type is "tuple[__main__.C[builtins.int], builtins.str, builtins.int]" reveal_type(d.meth("test")) # N: Revealed type is "tuple[__main__.D, builtins.str, builtins.int]" [builtins fixtures/tuple.pyi] [case testTypingSelfRecursiveInit] from typing import Self class C: def __init__(self, other: Self) -> None: ... class D(C): ... reveal_type(C) # N: Revealed type is "def (other: __main__.C) -> __main__.C" reveal_type(D) # N: Revealed type is "def (other: __main__.D) -> __main__.D" [case testTypingSelfCorrectName] from typing import Self, List class C: Self = List[C] def meth(self) -> Self: ... reveal_type(C.meth) # N: Revealed type is "def (self: __main__.C) -> builtins.list[__main__.C]" [case testTypingSelfClassVar] from typing import Self, ClassVar, Generic, TypeVar class C: DEFAULT: ClassVar[Self] reveal_type(C.DEFAULT) # N: Revealed type is "__main__.C" T = TypeVar("T") class G(Generic[T]): BAD: ClassVar[Self] # E: ClassVar cannot contain Self type in generic classes reveal_type(G.BAD) # N: Revealed type is "__main__.G[Any]" [case testTypingSelfMetaClassDisabled] from typing import Self class Meta(type): def meth(cls) -> Self: ... # E: Self type cannot be used in a metaclass [case testTypingSelfNonAnnotationUses] from typing import Self, List, cast class C: A = List[Self] # E: Self type cannot be used in type alias target B = cast(Self, ...) def meth(self) -> A: ... class D(C): ... reveal_type(D().meth()) # N: Revealed type is "builtins.list[Any]" reveal_type(D().B) # N: Revealed type is "__main__.D" [case testTypingSelfInternalSafe] from typing import Self class C: x: Self def __init__(self, x: C) -> None: self.x = x # E: Incompatible types in assignment (expression has type "C", variable has type "Self") [case testTypingSelfRedundantAllowed] from typing import Self, Type class C: def f(self: Self) -> Self: d: Defer class Defer: ... return self @classmethod def g(cls: Type[Self]) -> Self: d: DeferAgain class DeferAgain: ... return cls() [builtins fixtures/classmethod.pyi] [case testTypingSelfRedundantAllowed_pep585] from typing import Self class C: def f(self: Self) -> Self: d: Defer class Defer: ... return self @classmethod def g(cls: type[Self]) -> Self: d: DeferAgain class DeferAgain: ... return cls() [builtins fixtures/classmethod.pyi] [case testTypingSelfRedundantWarning] # mypy: enable-error-code="redundant-self" from typing import Self, Type class C: def copy(self: Self) -> Self: # E: Redundant "Self" annotation for the first method argument d: Defer class Defer: ... return self @classmethod def g(cls: Type[Self]) -> Self: # E: Redundant "Self" annotation for the first method argument d: DeferAgain class DeferAgain: ... return cls() [builtins fixtures/classmethod.pyi] [case testTypingSelfRedundantWarning_pep585] # mypy: enable-error-code="redundant-self" from typing import Self class C: def copy(self: Self) -> Self: # E: Redundant "Self" annotation for the first method argument d: Defer class Defer: ... return self @classmethod def g(cls: type[Self]) -> Self: # E: Redundant "Self" annotation for the first method argument d: DeferAgain class DeferAgain: ... return cls() [builtins fixtures/classmethod.pyi] [case testTypingSelfAssertType] from typing import Self, assert_type class C: def foo(self) -> None: assert_type(self, Self) # E: Expression is of type "C", not "Self" assert_type(C(), Self) # E: Expression is of type "C", not "Self" def bar(self) -> Self: assert_type(self, Self) # OK assert_type(C(), Self) # E: Expression is of type "C", not "Self" return self [case testTypingSelfTypeVarClash] from typing import Self, TypeVar, Tuple S = TypeVar("S") class C: def bar(self) -> Self: ... def foo(self, x: S) -> Tuple[Self, S]: ... reveal_type(C.foo) # N: Revealed type is "def [Self <: __main__.C, S] (self: Self`1, x: S`2) -> tuple[Self`1, S`2]" reveal_type(C().foo(42)) # N: Revealed type is "tuple[__main__.C, builtins.int]" [builtins fixtures/tuple.pyi] [case testTypingSelfTypeVarClashAttr] from typing import Self, TypeVar, Tuple, Callable class Defer(This): ... S = TypeVar("S") class C: def bar(self) -> Self: ... foo: Callable[[S, Self], Tuple[Self, S]] reveal_type(C().foo) # N: Revealed type is "def [S] (S`2, __main__.C) -> tuple[__main__.C, S`2]" reveal_type(C().foo(42, C())) # N: Revealed type is "tuple[__main__.C, builtins.int]" class This: ... [builtins fixtures/tuple.pyi] [case testTypingSelfAttrOldVsNewStyle] from typing import Self, TypeVar T = TypeVar("T", bound='C') class C: x: Self def foo(self: T) -> T: return self.x def bar(self: T) -> T: self.x = self return self def baz(self: Self) -> None: self.x = self def bad(self) -> None: # This is unfortunate, but required by PEP 484 self.x = self # E: Incompatible types in assignment (expression has type "C", variable has type "Self") [case testTypingSelfClashInBodies] from typing import Self, TypeVar T = TypeVar("T") class C: def very_bad(self, x: T) -> None: self.x = x # E: Incompatible types in assignment (expression has type "T", variable has type "Self") x: Self def baz(self: Self, x: T) -> None: y: T = x [case testTypingSelfClashUnrelated] from typing import Self, Generic, TypeVar class B: ... T = TypeVar("T", bound=B) class C(Generic[T]): def __init__(self, val: T) -> None: self.val = val def foo(self) -> Self: ... def test(x: C[T]) -> T: reveal_type(x.val) # N: Revealed type is "T`-1" return x.val [case testTypingSelfGenericBound] from typing import Self, Generic, TypeVar T = TypeVar("T") class C(Generic[T]): val: T def foo(self) -> Self: reveal_type(self.val) # N: Revealed type is "T`1" return self [case testTypingSelfDifferentImport] import typing as t class Foo: def foo(self) -> t.Self: return self @classmethod def bar(cls) -> t.Self: return cls() [builtins fixtures/classmethod.pyi] [case testTypingSelfAllowAliasUseInFinalClasses] from typing import Self, final @final class C: def meth(self) -> Self: return C() # OK for final classes [case testTypingSelfCallableClassVar] from typing import Self, ClassVar, Callable, TypeVar class C: f: ClassVar[Callable[[Self], Self]] class D(C): ... reveal_type(D.f) # N: Revealed type is "def (__main__.D) -> __main__.D" reveal_type(D().f) # N: Revealed type is "def () -> __main__.D" [case testSelfTypeCallableClassVarOldStyle] from typing import ClassVar, Callable, TypeVar T = TypeVar("T") class C: f: ClassVar[Callable[[T], T]] class D(C): ... reveal_type(D.f) # N: Revealed type is "def [T] (T`3) -> T`3" reveal_type(D().f) # N: Revealed type is "def () -> __main__.D" [case testTypingSelfOnSuperTypeVarValues] from typing import Self, Generic, TypeVar T = TypeVar("T", int, str) class B: def copy(self) -> Self: ... class C(B, Generic[T]): def copy(self) -> Self: inst = super().copy() reveal_type(inst) # N: Revealed type is "Self`0" return inst [case testTypingSelfWithValuesExpansion] from typing import Self, Generic, TypeVar class A: pass class B: pass T = TypeVar("T", A, B) class C(Generic[T]): val: T def foo(self, x: T) -> None: ... def bar(self, x: T) -> Self: reveal_type(self.foo) # N: Revealed type is "def (x: __main__.A)" \ # N: Revealed type is "def (x: __main__.B)" self.foo(x) return self def baz(self: Self, x: T) -> None: reveal_type(self.val) # N: Revealed type is "__main__.A" \ # N: Revealed type is "__main__.B" self.val = x [case testNarrowSelfType] from typing import Self, Union class A: ... class B: def f1(self, v: Union[Self, A]) -> A: if isinstance(v, B): return A() else: return v def f2(self, v: Union[Self, A]) -> A: if isinstance(v, B): return A() else: return B() # E: Incompatible return value type (got "B", expected "A") [builtins fixtures/isinstancelist.pyi] [case testAttributeOnSelfAttributeInSubclass] from typing import List, Self class A: x: Self xs: List[Self] class B(A): extra: int def meth(self) -> None: reveal_type(self.x) # N: Revealed type is "Self`0" reveal_type(self.xs[0]) # N: Revealed type is "Self`0" reveal_type(self.x.extra) # N: Revealed type is "builtins.int" reveal_type(self.xs[0].extra) # N: Revealed type is "builtins.int" [builtins fixtures/list.pyi] [case testSelfTypesWithParamSpecExtract] from typing import Any, Callable, Generic, TypeVar from typing_extensions import ParamSpec P = ParamSpec("P") F = TypeVar("F", bound=Callable[..., Any]) class Example(Generic[F]): def __init__(self, fn: F) -> None: ... def __call__(self: Example[Callable[P, Any]], *args: P.args, **kwargs: P.kwargs) -> None: ... def test_fn(a: int, b: str) -> None: ... example = Example(test_fn) example() # E: Missing positional arguments "a", "b" in call to "__call__" of "Example" example(1, "b") # OK [builtins fixtures/list.pyi] [case testSelfTypesWithParamSpecInfer] from typing import TypeVar, Protocol, Type, Callable from typing_extensions import ParamSpec R = TypeVar("R", covariant=True) P = ParamSpec("P") class AsyncP(Protocol[P]): def meth(self, *args: P.args, **kwargs: P.kwargs) -> None: ... class Async: @classmethod def async_func(cls: Type[AsyncP[P]]) -> Callable[P, int]: ... class Add(Async): def meth(self, x: int, y: int) -> None: ... reveal_type(Add.async_func()) # N: Revealed type is "def (x: builtins.int, y: builtins.int) -> builtins.int" reveal_type(Add().async_func()) # N: Revealed type is "def (x: builtins.int, y: builtins.int) -> builtins.int" [builtins fixtures/classmethod.pyi] [case testSelfTypeMethodOnClassObject] from typing import Self class Object: # Needed to mimic object in typeshed ref: Self class Foo: def foo(self) -> Self: return self class Ben(Object): MY_MAP = { "foo": Foo.foo, } @classmethod def doit(cls) -> Foo: reveal_type(cls.MY_MAP) # N: Revealed type is "builtins.dict[builtins.str, def [Self <: __main__.Foo] (self: Self`1) -> Self`1]" foo_method = cls.MY_MAP["foo"] return foo_method(Foo()) [builtins fixtures/isinstancelist.pyi] [case testSelfTypeOnGenericClassObjectNewStyleBound] from typing import Generic, TypeVar, Self T = TypeVar("T") S = TypeVar("S") class B(Generic[T, S]): def copy(self) -> Self: ... b: B[int, str] reveal_type(B.copy(b)) # N: Revealed type is "__main__.B[builtins.int, builtins.str]" class C(B[T, S]): ... c: C[int, str] reveal_type(C.copy(c)) # N: Revealed type is "__main__.C[builtins.int, builtins.str]" B.copy(42) # E: Value of type variable "Self" of "copy" of "B" cannot be "int" C.copy(42) # E: Value of type variable "Self" of "copy" of "B" cannot be "int" [builtins fixtures/tuple.pyi] [case testRecursiveSelfTypeCallMethodNoCrash] from typing import Callable, TypeVar T = TypeVar("T") class Partial: def __call__(self: Callable[..., T]) -> T: ... class Partial2: def __call__(self: Callable[..., T], x: T) -> T: ... p: Partial reveal_type(p()) # N: Revealed type is "Never" p2: Partial2 reveal_type(p2(42)) # N: Revealed type is "builtins.int" [case testAccessingSelfClassVarInClassMethod] from typing import Self, ClassVar, Type, TypeVar T = TypeVar("T", bound="Foo") class Foo: instance: ClassVar[Self] @classmethod def get_instance(cls) -> Self: return reveal_type(cls.instance) # N: Revealed type is "Self`0" @classmethod def get_instance_old(cls: Type[T]) -> T: return reveal_type(cls.instance) # N: Revealed type is "T`-1" class Bar(Foo): extra: int @classmethod def get_instance(cls) -> Self: reveal_type(cls.instance.extra) # N: Revealed type is "builtins.int" return cls.instance @classmethod def other(cls) -> None: reveal_type(cls.instance) # N: Revealed type is "Self`0" reveal_type(cls.instance.extra) # N: Revealed type is "builtins.int" reveal_type(Bar.instance) # N: Revealed type is "__main__.Bar" [builtins fixtures/classmethod.pyi] [case testAccessingSelfClassVarInClassMethodTuple] from typing import Self, ClassVar, Tuple class C(Tuple[int, str]): x: Self y: ClassVar[Self] @classmethod def bar(cls) -> None: reveal_type(cls.y) # N: Revealed type is "Self`0" @classmethod def bar_self(self) -> Self: return reveal_type(self.y) # N: Revealed type is "Self`0" c: C reveal_type(c.x) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.C]" reveal_type(c.y) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.C]" reveal_type(C.y) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=__main__.C]" C.x # E: Access to generic instance variables via class is ambiguous [builtins fixtures/classmethod.pyi] [case testAccessingTypingSelfUnion] from typing import Self, Union class C: x: Self class D: x: int x: Union[C, D] reveal_type(x.x) # N: Revealed type is "__main__.C | builtins.int" [case testCallableProtocolTypingSelf] from typing import Protocol, Self class MyProtocol(Protocol): __name__: str def __call__( self: Self, ) -> None: ... def test() -> None: ... value: MyProtocol = test [case testCallableProtocolOldSelf] from typing import Protocol, TypeVar Self = TypeVar("Self", bound="MyProtocol") class MyProtocol(Protocol): __name__: str def __call__( self: Self, ) -> None: ... def test() -> None: ... value: MyProtocol = test [case testSelfTypeUnionIter] from typing import Self, Iterator, Generic, TypeVar, Union T = TypeVar("T") class range(Generic[T]): def __iter__(self) -> Self: ... def __next__(self) -> T: ... class count: def __iter__(self) -> Iterator[int]: ... def foo(x: Union[range[int], count]) -> None: for item in x: reveal_type(item) # N: Revealed type is "builtins.int" [case testGenericDescriptorWithSelfTypeAnnotationsAndOverloads] from __future__ import annotations from typing import Any, overload, Callable, TypeVar, Generic, ParamSpec from typing_extensions import Concatenate C = TypeVar("C", bound=Callable[..., Any]) S = TypeVar("S") P = ParamSpec("P") R = TypeVar("R") class Descriptor(Generic[C]): def __init__(self, impl: C) -> None: ... @overload def __get__( self: Descriptor[C], instance: None, owner: type | None ) -> Descriptor[C]: ... @overload def __get__( self: Descriptor[Callable[Concatenate[S, P], R]], instance: S, owner: type | None, ) -> Callable[P, R]: ... def __get__(self, *args, **kwargs): ... class Test: @Descriptor def method(self, foo: int, bar: str) -> bytes: ... reveal_type(Test().method) # N: Revealed type is "def (foo: builtins.int, bar: builtins.str) -> builtins.bytes" class Test2: @Descriptor def method(self, foo: int, *, bar: str) -> bytes: ... reveal_type(Test2().method) # N: Revealed type is "def (foo: builtins.int, *, bar: builtins.str) -> builtins.bytes" [builtins fixtures/tuple.pyi] [case testSelfInMultipleInheritance] from typing_extensions import Self class A: foo: int def method(self: Self, other: Self) -> None: self.foo other.foo class B: bar: str def method(self: Self, other: Self) -> None: self.bar other.bar class C(A, B): # OK: both methods take Self pass [builtins fixtures/tuple.pyi] [case testSelfTypeClassMethodNotSilentlyErased] from typing import Self, Optional class X: _inst: Optional[Self] = None @classmethod def default(cls) -> Self: reveal_type(cls._inst) # N: Revealed type is "Self`0 | None" if cls._inst is None: cls._inst = cls() return cls._inst reveal_type(X._inst) # E: Access to generic instance variables via class is ambiguous \ # N: Revealed type is "__main__.X | None" reveal_type(X()._inst) # N: Revealed type is "__main__.X | None" class Y(X): ... reveal_type(Y._inst) # E: Access to generic instance variables via class is ambiguous \ # N: Revealed type is "__main__.Y | None" reveal_type(Y()._inst) # N: Revealed type is "__main__.Y | None" [builtins fixtures/tuple.pyi] [case testSelfInFuncDecoratedClassmethod] from collections.abc import Callable from typing import Self, TypeVar T = TypeVar("T") def debug(make: Callable[[type[T]], T]) -> Callable[[type[T]], T]: return make class Foo: @classmethod @debug def make(cls) -> Self: return cls() class Bar(Foo): ... reveal_type(Foo.make()) # N: Revealed type is "__main__.Foo" reveal_type(Foo().make()) # N: Revealed type is "__main__.Foo" reveal_type(Bar.make()) # N: Revealed type is "__main__.Bar" reveal_type(Bar().make()) # N: Revealed type is "__main__.Bar" [builtins fixtures/tuple.pyi] [case testSelfInClassDecoratedClassmethod] from typing import Callable, Generic, TypeVar, Self T = TypeVar("T") class W(Generic[T]): def __init__(self, fn: Callable[..., T]) -> None: ... def __call__(self) -> T: ... class Check: @W def foo(self) -> Self: ... reveal_type(Check.foo()) # N: Revealed type is "def () -> __main__.Check" reveal_type(Check().foo()) # N: Revealed type is "__main__.Check" [builtins fixtures/tuple.pyi] [case testSelfInClassmethodWithOtherSelfMethod] from typing import Any, Callable, Self, TypeVar _C = TypeVar("_C", bound=Callable[..., Any]) def identity(func: _C, /) -> _C: return func class A: def meth(self) -> Self: ... @classmethod def other_meth(cls) -> Self: reveal_type(cls.meth) # N: Revealed type is "def [Self <: __main__.A] (self: Self`1) -> Self`1" reveal_type(A.meth) # N: Revealed type is "def [Self <: __main__.A] (self: Self`2) -> Self`2" return cls().meth() class B: @identity def meth(self) -> Self: ... @classmethod def other_meth(cls) -> Self: reveal_type(cls.meth) # N: Revealed type is "def [Self <: __main__.B] (self: Self`5) -> Self`5" reveal_type(B.meth) # N: Revealed type is "def [Self <: __main__.B] (self: Self`6) -> Self`6" return cls().meth() class C: @classmethod def other_meth(cls) -> Self: ... def meth(self) -> Self: reveal_type(self.other_meth) # N: Revealed type is "def () -> Self`0" reveal_type(type(self).other_meth) # N: Revealed type is "def () -> Self`0" return self.other_meth() [builtins fixtures/tuple.pyi] [case testSelfTypeUpperBoundFiler] from typing import Generic, TypeVar, overload, Sequence class B: ... class C(B): ... TB = TypeVar("TB", bound=B) TC = TypeVar("TC", bound=C) class G(Generic[TB]): @overload def test(self: G[TC]) -> list[TC]: ... @overload def test(self: G[TB]) -> Sequence[TB]: ... def test(self): ... class D1(B): ... class D2(C): ... gb: G[D1] gc: G[D2] reveal_type(gb.test()) # N: Revealed type is "typing.Sequence[__main__.D1]" reveal_type(gc.test()) # N: Revealed type is "builtins.list[__main__.D2]" [builtins fixtures/list.pyi] [case testEnumImplicitlyFinalForSelfType] from enum import Enum from typing import Self # This enum has members and so is implicitly final. # Foo and Self are interchangeable within the class. class Foo(Enum): A = 1 @classmethod def foo(cls) -> Self: return Foo.A @classmethod def foo2(cls) -> Self: return cls.bar() @classmethod def bar(cls) -> Foo: ... # This enum is empty and should not be assignable to Self class Bar(Enum): @classmethod def foo(cls) -> Self: return cls.bar() # E: Incompatible return value type (got "Bar", expected "Self") @classmethod def bar(cls) -> Bar: ... [builtins fixtures/classmethod.pyi]