-- Create Instance [case testCanCreateTypedDictInstanceWithKeywordArguments] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) p = Point(x=42, y=1337) reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})" # Use values() to check fallback value type. reveal_type(p.values()) # N: Revealed type is "typing.Iterable[builtins.object]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [targets __main__] [case testCanCreateTypedDictInstanceWithDictCall] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) p = Point(dict(x=42, y=1337)) reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})" # Use values() to check fallback value type. reveal_type(p.values()) # N: Revealed type is "typing.Iterable[builtins.object]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictInstanceWithDictLiteral] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) p = Point({'x': 42, 'y': 1337}) reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})" # Use values() to check fallback value type. reveal_type(p.values()) # N: Revealed type is "typing.Iterable[builtins.object]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictInstanceWithNoArguments] from typing import TypedDict, TypeVar, Union EmptyDict = TypedDict('EmptyDict', {}) p = EmptyDict() reveal_type(p) # N: Revealed type is "TypedDict('__main__.EmptyDict', {})" reveal_type(p.values()) # N: Revealed type is "typing.Iterable[builtins.object]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Create Instance (Errors) [case testCannotCreateTypedDictInstanceWithUnknownArgumentPattern] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) p = Point(42, 1337) # E: Expected keyword arguments, {...}, or dict(...) in TypedDict constructor [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictInstanceNonLiteralItemName] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) x = 'x' p = Point({x: 42, 'y': 1337}) # E: Expected TypedDict key to be string literal [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictInstanceWithExtraItems] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) p = Point(x=42, y=1337, z=666) # E: Extra key "z" for TypedDict "Point" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictInstanceWithMissingItems] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) p = Point(x=42) # E: Missing key "y" for TypedDict "Point" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictInstanceWithIncompatibleItemType] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) p = Point(x='meaning_of_life', y=1337) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictInstanceWithInlineTypedDict] from typing import TypedDict D = TypedDict('D', { 'x': TypedDict('E', { # E: Use dict literal for nested TypedDict 'y': int }) }) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Define TypedDict (Class syntax) [case testCanCreateTypedDictWithClass] from typing import TypedDict class Point(TypedDict): x: int y: int p = Point(x=42, y=1337) reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithSubclass] from typing import TypedDict class Point1D(TypedDict): x: int class Point2D(Point1D): y: int r: Point1D p: Point2D reveal_type(r) # N: Revealed type is "TypedDict('__main__.Point1D', {'x': builtins.int})" reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point2D', {'x': builtins.int, 'y': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithSubclass2] from typing import TypedDict class Point1D(TypedDict): x: int class Point2D(TypedDict, Point1D): # We also allow to include TypedDict in bases, it is simply ignored at runtime y: int p: Point2D reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point2D', {'x': builtins.int, 'y': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictClassEmpty] from typing import TypedDict class EmptyDict(TypedDict): pass p = EmptyDict() reveal_type(p) # N: Revealed type is "TypedDict('__main__.EmptyDict', {})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithClassFunctionBases] # Test that we can use class-syntax to merge function-based TypedDicts from typing import TypedDict MovieBase1 = TypedDict( 'MovieBase1', {'name': str, 'year': int}) MovieBase2 = TypedDict( 'MovieBase2', {'based_on': str}, total=False) class Movie(MovieBase1, MovieBase2): pass def foo(x): # type: (Movie) -> None pass foo({}) # E: Missing keys ("name", "year") for TypedDict "Movie" foo({'name': 'lol', 'year': 2009, 'based_on': 0}) # E: Incompatible types (expression has type "int", TypedDict item "based_on" has type "str") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Define TypedDict (Class syntax errors) [case testCannotCreateTypedDictWithClassOtherBases] from typing import TypedDict class A: pass class Point1D(TypedDict, A): # E: All bases of a new TypedDict must be TypedDict types x: int class Point2D(Point1D, A): # E: All bases of a new TypedDict must be TypedDict types y: int p: Point2D reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point2D', {'x': builtins.int, 'y': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictWithDuplicateBases] # https://github.com/python/mypy/issues/3673 from typing import TypedDict class A(TypedDict): x: str y: int class B(A, A): # E: Duplicate base class "A" z: str class C(TypedDict, TypedDict): # E: Duplicate base class "TypedDict" c1: int [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictWithClassWithOtherStuff] from typing import TypedDict class Point(TypedDict): x: int y: int = 1 # E: Right hand side values are not supported in TypedDict def f(): pass # E: Invalid statement in TypedDict definition; expected "field_name: field_type" z = int # E: Invalid statement in TypedDict definition; expected "field_name: field_type" p = Point(x=42, y=1337, z='whatever') reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int, 'z': Any})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictWithClassWithFunctionUsedToCrash] # https://github.com/python/mypy/issues/11079 from typing import TypedDict class D(TypedDict): y: int def x(self, key: int): # E: Invalid statement in TypedDict definition; expected "field_name: field_type" pass d = D(y=1) reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'y': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictWithDecoratedFunction] # flags: --disallow-any-expr # https://github.com/python/mypy/issues/13066 from typing import TypedDict class D(TypedDict): @classmethod # E: Invalid statement in TypedDict definition; expected "field_name: field_type" def m(self) -> D: pass d = D() reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictDecoratorUndefinedNames] from typing import TypedDict @abc # E: Name "abc" is not defined @efg.hij # E: Name "efg" is not defined @klm[nop] # E: Name "klm" is not defined \ # E: Name "nop" is not defined @qrs.tuv[wxy] # E: Name "qrs" is not defined \ # E: Name "wxy" is not defined class A(TypedDict): x: int [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictWithClassmethodAlternativeConstructorDoesNotCrash] # https://github.com/python/mypy/issues/5653 from typing import TypedDict class Foo(TypedDict): bar: str @classmethod # E: Invalid statement in TypedDict definition; expected "field_name: field_type" def baz(cls) -> "Foo": ... [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictTypeWithUnderscoreItemName] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int, '_fallback': object}) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithClassUnderscores] from typing import TypedDict class Point(TypedDict): x: int _y: int p: Point reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, '_y': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictWithDuplicateKey1] from typing import TypedDict class Bad(TypedDict): x: int x: str # E: Duplicate TypedDict key "x" b: Bad reveal_type(b) # N: Revealed type is "TypedDict('__main__.Bad', {'x': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictWithDuplicateKey2] from typing import TypedDict D1 = TypedDict("D1", { "x": int, "x": int, # E: Duplicate TypedDict key "x" }) D2 = TypedDict("D2", {"x": int, "x": str}) # E: Duplicate TypedDict key "x" d1: D1 d2: D2 reveal_type(d1) # N: Revealed type is "TypedDict('__main__.D1', {'x': builtins.int})" reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'x': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithClassOverwriting] from typing import TypedDict class Point1(TypedDict): x: int class Point2(TypedDict): x: float class Bad(Point1, Point2): # E: Incompatible definitions of field "x" in base classes "Point2" and "Point1" pass b: Bad reveal_type(b) # N: Revealed type is "TypedDict('__main__.Bad', {'x': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithClassOverwriting2] from typing import TypedDict class Point1(TypedDict): x: int class Point2(Point1): x: float # E: Definition of field "x" incompatible with base class "Point1" p2: Point2 reveal_type(p2) # N: Revealed type is "TypedDict('__main__.Point2', {'x': builtins.float})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithClassOverwriting3] from typing import TypedDict class Point1(TypedDict): x: float class Point2(Point1): x: int # E: Definition of field "x" incompatible with base class "Point1" p2: Point2 reveal_type(p2) # N: Revealed type is "TypedDict('__main__.Point2', {'x': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithClassOverwriting4] from typing import TypedDict class Point1(TypedDict): x: int class Point2(TypedDict, total=False): x: int class Bad(Point1, Point2): # E: Field "x" is required in base class "Point1" but can be deleted in base class "Point2" pass b: Bad reveal_type(b) # N: Revealed type is "TypedDict('__main__.Bad', {'x': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithClassOverwriting5] from typing import TypedDict class Point1(TypedDict): x: int class Point2(Point1, total=False): x: int # E: Field "x" is required in base class "Point1" p2: Point2 reveal_type(p2) # N: Revealed type is "TypedDict('__main__.Point2', {'x'?: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithClassOverwriting6] from typing import TypedDict class Point1(TypedDict, total=False): x: int class Point2(TypedDict): x: int class Bad(Point1, Point2): # E: Field "x" is required in base class "Point2" but can be deleted in base class "Point1" pass b: Bad reveal_type(b) # N: Revealed type is "TypedDict('__main__.Bad', {'x'?: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithClassOverwriting7] from typing import TypedDict class Point1(TypedDict, total=False): x: int class Point2(Point1): x: int # E: Field "x" can be deleted in base class "Point1" p2: Point2 reveal_type(p2) # N: Revealed type is "TypedDict('__main__.Point2', {'x': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Subtyping [case testCanConvertTypedDictToItself] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) def identity(p: Point) -> Point: return p [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanConvertTypedDictToEquivalentTypedDict] from typing import TypedDict PointA = TypedDict('PointA', {'x': int, 'y': int}) PointB = TypedDict('PointB', {'x': int, 'y': int}) def identity(p: PointA) -> PointB: return p [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotConvertTypedDictToSimilarTypedDictWithNarrowerItemTypes] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) ObjectPoint = TypedDict('ObjectPoint', {'x': object, 'y': object}) def convert(op: ObjectPoint) -> Point: return op # E: Incompatible return value type (got "ObjectPoint", expected "Point") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotConvertTypedDictToSimilarTypedDictWithWiderItemTypes] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) ObjectPoint = TypedDict('ObjectPoint', {'x': object, 'y': object}) def convert(p: Point) -> ObjectPoint: return p # E: Incompatible return value type (got "Point", expected "ObjectPoint") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotConvertTypedDictToSimilarTypedDictWithIncompatibleItemTypes] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) Chameleon = TypedDict('Chameleon', {'x': str, 'y': str}) def convert(p: Point) -> Chameleon: return p # E: Incompatible return value type (got "Point", expected "Chameleon") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanConvertTypedDictToNarrowerTypedDict] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) Point1D = TypedDict('Point1D', {'x': int}) def narrow(p: Point) -> Point1D: return p [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotConvertTypedDictToWiderTypedDict] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) Point3D = TypedDict('Point3D', {'x': int, 'y': int, 'z': int}) def widen(p: Point) -> Point3D: return p # E: Incompatible return value type (got "Point", expected "Point3D") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanConvertTypedDictToCompatibleMapping] from typing import Mapping, TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) def as_mapping(p: Point) -> Mapping[str, object]: return p [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotConvertTypedDictToIncompatibleMapping] from typing import Mapping, TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) def as_mapping(p: Point) -> Mapping[str, int]: return p # E: Incompatible return value type (got "Point", expected "Mapping[str, int]") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAcceptsIntForFloatDuckTypes] from typing import Any, Mapping, TypedDict Point = TypedDict('Point', {'x': float, 'y': float}) def create_point() -> Point: return Point(x=1, y=2) reveal_type(Point(x=1, y=2)) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.float, 'y': builtins.float})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictDoesNotAcceptsFloatForInt] from typing import Any, Mapping, TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) def create_point() -> Point: return Point(x=1.2, y=2.5) [out] main:4: error: Incompatible types (expression has type "float", TypedDict item "x" has type "int") main:4: error: Incompatible types (expression has type "float", TypedDict item "y" has type "int") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAcceptsAnyType] from typing import Any, Mapping, TypedDict Point = TypedDict('Point', {'x': float, 'y': float}) def create_point(something: Any) -> Point: return Point({ 'x': something.x, 'y': something.y }) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictValueTypeContext] from typing import List, TypedDict D = TypedDict('D', {'x': List[int]}) reveal_type(D(x=[])) # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.list[builtins.int]})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotConvertTypedDictToDictOrMutableMapping] from typing import Dict, MutableMapping, TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) def as_dict(p: Point) -> Dict[str, int]: return p # E: Incompatible return value type (got "Point", expected "dict[str, int]") def as_mutable_mapping(p: Point) -> MutableMapping[str, object]: return p # E: Incompatible return value type (got "Point", expected "MutableMapping[str, object]") [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testCanConvertTypedDictToAny] from typing import Any, TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) def unprotect(p: Point) -> Any: return p [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testAnonymousTypedDictInErrorMessages] from typing import TypedDict A = TypedDict('A', {'x': int, 'y': str}) B = TypedDict('B', {'x': int, 'z': str, 'a': int}) C = TypedDict('C', {'x': int, 'z': str, 'a': str}) a: A b: B c: C def f(a: A) -> None: pass l = [a, b] # Join generates an anonymous TypedDict f(l) # E: Argument 1 to "f" has incompatible type "list[TypedDict({'x': int})]"; expected "A" ll = [b, c] f(ll) # E: Argument 1 to "f" has incompatible type "list[TypedDict({'x': int, 'z': str, 'a'=: object})]"; expected "A" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictWithSimpleProtocol] from typing import Protocol, TypedDict class StrObjectMap(Protocol): def __getitem__(self, key: str) -> object: ... class StrIntMap(Protocol): def __getitem__(self, key: str) -> int: ... A = TypedDict('A', {'x': int, 'y': int}) B = TypedDict('B', {'x': int, 'y': str}) def fun(arg: StrObjectMap) -> None: ... def fun2(arg: StrIntMap) -> None: ... a: A b: B fun(a) fun(b) fun2(a) # Error [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [out] main:17: error: Argument 1 to "fun2" has incompatible type "A"; expected "StrIntMap" main:17: note: Following member(s) of "A" have conflicts: main:17: note: Expected: main:17: note: def __getitem__(self, str, /) -> int main:17: note: Got: main:17: note: def __getitem__(self, str, /) -> object [case testTypedDictWithSimpleProtocolInference] from typing import Protocol, TypedDict, TypeVar T_co = TypeVar('T_co', covariant=True) T = TypeVar('T') class StrMap(Protocol[T_co]): def __getitem__(self, key: str) -> T_co: ... A = TypedDict('A', {'x': int, 'y': int}) B = TypedDict('B', {'x': int, 'y': str}) def fun(arg: StrMap[T]) -> T: return arg['whatever'] a: A b: B reveal_type(fun(a)) # N: Revealed type is "builtins.object" reveal_type(fun(b)) # N: Revealed type is "builtins.object" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Join [case testJoinOfTypedDictHasOnlyCommonKeysAndNewFallback] from typing import TypedDict TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int}) Point3D = TypedDict('Point3D', {'x': int, 'y': int, 'z': int}) p1 = TaggedPoint(type='2d', x=0, y=0) p2 = Point3D(x=1, y=1, z=1) joined_points = [p1, p2][0] reveal_type(p1.values()) # N: Revealed type is "typing.Iterable[builtins.object]" reveal_type(p2.values()) # N: Revealed type is "typing.Iterable[builtins.object]" reveal_type(joined_points) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testJoinOfTypedDictJoinsNonequivalentKeys] from typing import TypedDict, NotRequired CellWithInt = TypedDict('CellWithInt', {'value': object, 'meta': int}) CellWithString = TypedDict('CellWithString', {'value': object, 'meta': str}) CellWithNonRequiredInt = TypedDict('CellWithNonRequiredInt', {'value': object, 'meta': NotRequired[int]}) CellWithNonRequiredString = TypedDict('CellWithNonRequiredString', {'value': object, 'meta': NotRequired[str]}) c1 = CellWithInt(value=1, meta=42) c2 = CellWithString(value=2, meta='turtle doves') c3 = CellWithNonRequiredInt(value=1) c4 = CellWithNonRequiredString(value=2) j12 = [c1, c2] j14 = [c1, c4] j32 = [c3, c2] j34 = [c3, c4] reveal_type(c1) # N: Revealed type is "TypedDict('__main__.CellWithInt', {'value': builtins.object, 'meta': builtins.int})" reveal_type(c2) # N: Revealed type is "TypedDict('__main__.CellWithString', {'value': builtins.object, 'meta': builtins.str})" reveal_type(c3) # N: Revealed type is "TypedDict('__main__.CellWithNonRequiredInt', {'value': builtins.object, 'meta'?: builtins.int})" reveal_type(c4) # N: Revealed type is "TypedDict('__main__.CellWithNonRequiredString', {'value': builtins.object, 'meta'?: builtins.str})" reveal_type(j12) # N: Revealed type is "builtins.list[TypedDict({'value': builtins.object, 'meta'=: builtins.object})]" reveal_type(j14) # N: Revealed type is "builtins.list[TypedDict({'value': builtins.object, 'meta'?=: builtins.object})]" reveal_type(j32) # N: Revealed type is "builtins.list[TypedDict({'value': builtins.object, 'meta'?=: builtins.object})]" reveal_type(j34) # N: Revealed type is "builtins.list[TypedDict({'value': builtins.object, 'meta'?=: builtins.object})]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testJoinOfDisjointTypedDictsIsEmptyTypedDict] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) Cell = TypedDict('Cell', {'value': object}) d1 = Point(x=0, y=0) d2 = Cell(value='pear tree') joined_dicts = [d1, d2] reveal_type(d1) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})" reveal_type(d2) # N: Revealed type is "TypedDict('__main__.Cell', {'value': builtins.object})" reveal_type(joined_dicts) # N: Revealed type is "builtins.list[TypedDict({})]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testJoinOfTypedDictWithCompatibleMappingIsMapping] from typing import Mapping, TypedDict Cell = TypedDict('Cell', {'value': int}) left = Cell(value=42) right = {'score': 999} # type: Mapping[str, int] joined1 = [left, right] joined2 = [right, left] reveal_type(joined1) # N: Revealed type is "builtins.list[typing.Mapping[builtins.str, builtins.object]]" reveal_type(joined2) # N: Revealed type is "builtins.list[typing.Mapping[builtins.str, builtins.object]]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testJoinOfTypedDictWithCompatibleMappingSupertypeIsSupertype] from typing import Sized, TypedDict Cell = TypedDict('Cell', {'value': int}) left = Cell(value=42) right = {'score': 999} # type: Sized joined1 = [left, right] joined2 = [right, left] reveal_type(joined1) # N: Revealed type is "builtins.list[typing.Sized]" reveal_type(joined2) # N: Revealed type is "builtins.list[typing.Sized]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testJoinOfTypedDictWithIncompatibleTypeIsObject] from typing import Mapping, TypedDict Cell = TypedDict('Cell', {'value': int}) left = Cell(value=42) right = 42 joined1 = [left, right] joined2 = [right, left] reveal_type(joined1) # N: Revealed type is "builtins.list[builtins.object]" reveal_type(joined2) # N: Revealed type is "builtins.list[builtins.object]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Meet [case testMeetOfTypedDictsWithCompatibleCommonKeysHasAllKeysAndNewFallback] from typing import TypedDict, TypeVar, Callable XY = TypedDict('XY', {'x': int, 'y': int}) YZ = TypedDict('YZ', {'y': int, 'z': int}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: XY, y: YZ) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.int, 'z': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithAny] from typing import Any, TypedDict, TypeVar, Callable A = TypedDict('A', {'x': Any}) B = TypedDict('B', {'x': int}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def gAB(x: A, y: B) -> None: pass def gBA(x: B, y: A) -> None: pass reveal_type(f(gAB)) # N: Revealed type is "TypedDict({'x': builtins.int})" reveal_type(f(gBA)) # N: Revealed type is "TypedDict({'x': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictMissingAndAny] from typing import Any, TypedDict, TypeVar, Callable, ReadOnly T = TypeVar('T') def meet(x: Callable[[T, T], None]) -> T: pass A = TypedDict('A', {'x': Any}) B = TypedDict('B', {'y': Any}) C = TypedDict('C', {'y': Any}, total=False) def fAB(x: A, y: B) -> None: pass def fBA(x: B, y: A) -> None: pass def fAC(x: A, y: C) -> None: pass def fCA(x: C, y: A) -> None: pass if int(): reveal_type(meet(fAB)) # N: Revealed type is "TypedDict({'x': Any, 'y': Any})" if int(): reveal_type(meet(fBA)) # N: Revealed type is "TypedDict({'y': Any, 'x': Any})" if int(): reveal_type(meet(fAC)) # N: Revealed type is "TypedDict({'x': Any, 'y'?: Any})" if int(): reveal_type(meet(fCA)) # N: Revealed type is "TypedDict({'y'?: Any, 'x': Any})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsNotRequiredNeverAndAny] from typing import Any, NotRequired, TypedDict, TypeVar, Callable from typing_extensions import Never A = TypedDict('A', {'x': NotRequired[Any], 'y': NotRequired[Never]}) B = TypedDict('B', {'x': NotRequired[Never], 'y': NotRequired[Any]}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: A, y: B) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'?: Never, 'y'?: Never})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithIncompatibleCommonKeysIsUninhabited] from typing import TypedDict, TypeVar, Callable XYa = TypedDict('XYa', {'x': int, 'y': int}) YbZ = TypedDict('YbZ', {'y': object, 'z': int}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: XYa, y: YbZ) -> None: pass reveal_type(f(g)) # N: Revealed type is "Never" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithNoCommonKeysHasAllKeysAndNewFallback] from typing import TypedDict, TypeVar, Callable X = TypedDict('X', {'x': int}) Z = TypedDict('Z', {'z': int}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: X, y: Z) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x': builtins.int, 'z': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] # TODO: It would be more accurate for the meet to be TypedDict instead. [case testMeetOfTypedDictWithCompatibleMappingIsUninhabitedForNow] from typing import TypedDict, TypeVar, Callable, Mapping X = TypedDict('X', {'x': int}) M = Mapping[str, int] T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: X, y: M) -> None: pass reveal_type(f(g)) # N: Revealed type is "Never" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictWithIncompatibleMappingIsUninhabited] from typing import TypedDict, TypeVar, Callable, Mapping X = TypedDict('X', {'x': int}) M = Mapping[str, str] T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: X, y: M) -> None: pass reveal_type(f(g)) # N: Revealed type is "Never" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictWithCompatibleMappingSuperclassIsUninhabitedForNow] from typing import TypedDict, TypeVar, Callable, Iterable X = TypedDict('X', {'x': int}) I = Iterable[str] T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: X, y: I) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict('__main__.X', {'x': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithNonTotal] from typing import TypedDict, TypeVar, Callable XY = TypedDict('XY', {'x': int, 'y': int}, total=False) YZ = TypedDict('YZ', {'y': int, 'z': int}, total=False) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: XY, y: YZ) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'?: builtins.int, 'y'?: builtins.int, 'z'?: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithNonTotalAndTotal] from typing import TypedDict, TypeVar, Callable XY = TypedDict('XY', {'x': int}, total=False) YZ = TypedDict('YZ', {'y': int, 'z': int}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: XY, y: YZ) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'?: builtins.int, 'y': builtins.int, 'z': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithIncompatibleNonTotalAndTotal] from typing import TypedDict, TypeVar, Callable XY = TypedDict('XY', {'x': int, 'y': int}, total=False) YZ = TypedDict('YZ', {'y': int, 'z': int}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: XY, y: YZ) -> None: pass reveal_type(f(g)) # N: Revealed type is "Never" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Constraint Solver [case testTypedDictConstraintsAgainstIterable] from typing import TypedDict, TypeVar, Iterable T = TypeVar('T') def f(x: Iterable[T]) -> T: pass A = TypedDict('A', {'x': int}) a: A reveal_type(f(a)) # N: Revealed type is "builtins.str" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- TODO: Figure out some way to trigger the ConstraintBuilderVisitor.visit_typeddict_type() path. -- Special Method: __getitem__ [case testCanGetItemOfTypedDictWithValidStringLiteralKey] from typing import TypedDict TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int}) p = TaggedPoint(type='2d', x=42, y=1337) reveal_type(p['type']) # N: Revealed type is "builtins.str" reveal_type(p['x']) # N: Revealed type is "builtins.int" reveal_type(p['y']) # N: Revealed type is "builtins.int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotGetItemOfTypedDictWithInvalidStringLiteralKey] from typing import TypedDict TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int}) p: TaggedPoint p['typ'] # E: TypedDict "TaggedPoint" has no key "typ" \ # N: Did you mean "type"? [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotGetItemOfAnonymousTypedDictWithInvalidStringLiteralKey] from typing import TypedDict, TypeVar A = TypedDict('A', {'x': str, 'y': int, 'z': str}) B = TypedDict('B', {'x': str, 'z': int}) C = TypedDict('C', {'x': str, 'y': int, 'z': int}) T = TypeVar('T') def join(x: T, y: T) -> T: return x ab = join(A(x='', y=1, z=''), B(x='', z=1)) ac = join(A(x='', y=1, z=''), C(x='', y=0, z=1)) ab['y'] # E: "y" is not a valid TypedDict key; expected one of ("x", "z") ac['a'] # E: "a" is not a valid TypedDict key; expected one of ("x", "y", "z") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotGetItemOfTypedDictWithNonLiteralKey] from typing import TypedDict, Union TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int}) p = TaggedPoint(type='2d', x=42, y=1337) def get_coordinate(p: TaggedPoint, key: str) -> Union[str, int]: return p[key] # E: TypedDict key must be a string literal; expected one of ("type", "x", "y") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanGetItemOfTypedDictWithStringLiteralKeyInComprehension] from typing import TypedDict Data = TypedDict('Data', {'field1': int, 'field2': str, 'field3': str}) data: Data def is_str(value: object) -> bool: ... filtered_keys1 = [data[key] for key in ("field1", "field2", "field3")] filtered_keys2 = [key for key in ("field1", "field2", "field3") if is_str(data[key])] reveal_type(filtered_keys1) # N: Revealed type is "builtins.list[builtins.int | builtins.str]" reveal_type(filtered_keys2) # N: Revealed type is "builtins.list[builtins.str]" [builtins fixtures/for.pyi] [typing fixtures/typing-full.pyi] -- Special Method: __setitem__ [case testCanSetItemOfTypedDictWithValidStringLiteralKeyAndCompatibleValueType] from typing import TypedDict TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int}) p = TaggedPoint(type='2d', x=42, y=1337) p['type'] = 'two_d' p['x'] = 1 [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotSetItemOfTypedDictWithIncompatibleValueType] from typing import TypedDict TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int}) p = TaggedPoint(type='2d', x=42, y=1337) p['x'] = 'y' # E: Value of "x" has incompatible type "str"; expected "int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotSetItemOfTypedDictWithInvalidStringLiteralKey] from typing import TypedDict TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int}) p = TaggedPoint(type='2d', x=42, y=1337) p['z'] = 1 # E: TypedDict "TaggedPoint" has no key "z" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotSetItemOfTypedDictWithNonLiteralKey] from typing import TypedDict, Union TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int}) p = TaggedPoint(type='2d', x=42, y=1337) def set_coordinate(p: TaggedPoint, key: str, value: int) -> None: p[key] = value # E: TypedDict key must be a string literal; expected one of ("type", "x", "y") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- isinstance [case testTypedDictWithIsInstanceAndIsSubclass] from typing import TypedDict D = TypedDict('D', {'x': int}) d: object if isinstance(d, D): # E: Cannot use isinstance() with TypedDict type reveal_type(d) # N: Revealed type is "__main__.D" issubclass(object, D) # E: Cannot use issubclass() with TypedDict type [builtins fixtures/isinstancelist.pyi] [typing fixtures/typing-typeddict.pyi] -- Scoping [case testTypedDictInClassNamespace] # https://github.com/python/mypy/pull/2553#issuecomment-266474341 from typing import TypedDict class C: def f(self): A = TypedDict('A', {'x': int}) def g(self): A = TypedDict('A', {'y': int}) C.A # E: "type[C]" has no attribute "A" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictInFunction] from typing import TypedDict def f() -> None: A = TypedDict('A', {'x': int}) A # E: Name "A" is not defined [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Union simplification / proper subtype checks [case testTypedDictUnionSimplification] from typing import TypedDict, TypeVar, Union, Any, cast T = TypeVar('T') S = TypeVar('S') def u(x: T, y: S) -> Union[S, T]: pass C = TypedDict('C', {'a': int}) D = TypedDict('D', {'a': int, 'b': int}) E = TypedDict('E', {'a': str}) F = TypedDict('F', {'x': int}) G = TypedDict('G', {'a': Any}) c = C(a=1) d = D(a=1, b=1) e = E(a='') f = F(x=1) g = G(a=cast(Any, 1)) # Work around #2610 reveal_type(u(d, d)) # N: Revealed type is "TypedDict('__main__.D', {'a': builtins.int, 'b': builtins.int})" reveal_type(u(c, d)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int})" reveal_type(u(d, c)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int})" reveal_type(u(c, e)) # N: Revealed type is "TypedDict('__main__.E', {'a': builtins.str}) | TypedDict('__main__.C', {'a': builtins.int})" reveal_type(u(e, c)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int}) | TypedDict('__main__.E', {'a': builtins.str})" reveal_type(u(c, f)) # N: Revealed type is "TypedDict('__main__.F', {'x': builtins.int}) | TypedDict('__main__.C', {'a': builtins.int})" reveal_type(u(f, c)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int}) | TypedDict('__main__.F', {'x': builtins.int})" reveal_type(u(c, g)) # N: Revealed type is "TypedDict('__main__.G', {'a': Any}) | TypedDict('__main__.C', {'a': builtins.int})" reveal_type(u(g, c)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int}) | TypedDict('__main__.G', {'a': Any})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnionSimplification2] from typing import TypedDict, TypeVar, Union, Mapping, Any T = TypeVar('T') S = TypeVar('S') def u(x: T, y: S) -> Union[S, T]: pass C = TypedDict('C', {'a': int, 'b': int}) c = C(a=1, b=1) m_s_o: Mapping[str, object] m_s_s: Mapping[str, str] m_i_i: Mapping[int, int] m_s_a: Mapping[str, Any] reveal_type(u(c, m_s_o)) # N: Revealed type is "typing.Mapping[builtins.str, builtins.object]" reveal_type(u(m_s_o, c)) # N: Revealed type is "typing.Mapping[builtins.str, builtins.object]" reveal_type(u(c, m_s_s)) # N: Revealed type is "typing.Mapping[builtins.str, builtins.str] | TypedDict('__main__.C', {'a': builtins.int, 'b': builtins.int})" reveal_type(u(c, m_i_i)) # N: Revealed type is "typing.Mapping[builtins.int, builtins.int] | TypedDict('__main__.C', {'a': builtins.int, 'b': builtins.int})" reveal_type(u(c, m_s_a)) # N: Revealed type is "typing.Mapping[builtins.str, Any] | TypedDict('__main__.C', {'a': builtins.int, 'b': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnionUnambiguousCase] from typing import Union, Literal, Mapping, TypedDict, Any, cast A = TypedDict('A', {'@type': Literal['a-type'], 'a': str}) B = TypedDict('B', {'@type': Literal['b-type'], 'b': int}) c: Union[A, B] = {'@type': 'a-type', 'a': 'Test'} reveal_type(c) # N: Revealed type is "TypedDict('__main__.A', {'@type': Literal['a-type'], 'a': builtins.str}) | TypedDict('__main__.B', {'@type': Literal['b-type'], 'b': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnionAmbiguousCaseBothMatch] from typing import Union, Literal, Mapping, TypedDict, Any, cast A = TypedDict('A', {'@type': Literal['a-type'], 'value': str}) B = TypedDict('B', {'@type': Literal['b-type'], 'value': str}) c: Union[A, B] = {'@type': 'a-type', 'value': 'Test'} [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnionAmbiguousCaseNoMatch] from typing import Union, Literal, Mapping, TypedDict, Any, cast A = TypedDict('A', {'@type': Literal['a-type'], 'value': int}) B = TypedDict('B', {'@type': Literal['b-type'], 'value': int}) c: Union[A, B] = {'@type': 'a-type', 'value': 'Test'} # E: Type of TypedDict is ambiguous, none of ("A", "B") matches cleanly \ # E: Incompatible types in assignment (expression has type "dict[str, str]", variable has type "A | B") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnionWithNonTypedDictLiteralKey] from typing import Union, TypedDict class Foo(TypedDict): some: str name: str baz: Union[Foo, dict[int, float]] = {1: 5.2} baz2: Union[Foo, dict[int, float]] = {'some': 'x', 'name': 'y'} [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Use dict literals [case testTypedDictDictLiterals] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) def f(p: Point) -> None: if int(): p = {'x': 2, 'y': 3} p = {'x': 2} # E: Missing key "y" for TypedDict "Point" p = dict(x=2, y=3) f({'x': 1, 'y': 3}) f({'x': 1, 'y': 'z'}) # E: Incompatible types (expression has type "str", TypedDict item "y" has type "int") f(dict(x=1, y=3)) f(dict(x=1, y=3, z=4)) # E: Extra key "z" for TypedDict "Point" f(dict(x=1, y=3, z=4, a=5)) # E: Extra keys ("z", "a") for TypedDict "Point" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictExplicitTypes] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}) p1a: Point = {'x': 'hi'} # E: Missing key "y" for TypedDict "Point" p1b: Point = {} # E: Missing keys ("x", "y") for TypedDict "Point" p2: Point p2 = dict(x='bye') # E: Missing key "y" for TypedDict "Point" p3 = Point(x=1, y=2) if int(): p3 = {'x': 'hi'} # E: Missing key "y" for TypedDict "Point" p4: Point = {'x': 1, 'y': 2} [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateAnonymousTypedDictInstanceUsingDictLiteralWithExtraItems] from typing import TypedDict, TypeVar A = TypedDict('A', {'x': int, 'y': int}) B = TypedDict('B', {'x': int}) T = TypeVar('T') def join(x: T, y: T) -> T: return x ab = join(A(x=1, y=1), B(x=1)) if int(): ab = {'x': 1, 'z': 1} # E: Expected TypedDict key "x" but found keys ("x", "z") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateAnonymousTypedDictInstanceUsingDictLiteralWithMissingItems] from typing import TypedDict, TypeVar A = TypedDict('A', {'x': int, 'y': int, 'z': int}) B = TypedDict('B', {'x': int, 'y': int, 'z': str}) T = TypeVar('T') def join(x: T, y: T) -> T: return x ab = join(A(x=1, y=1, z=1), B(x=1, y=1, z='')) if int(): ab = {} # E: Expected TypedDict keys ("x", "y", "z") but found no keys [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Other TypedDict methods [case testTypedDictGetMethodOverloads] from typing import TypedDict from typing_extensions import Required, NotRequired class D(TypedDict): a: int b: NotRequired[str] def test(d: D) -> None: reveal_type(d.get) # N: Revealed type is "Overload(def (builtins.str) -> builtins.object, def (builtins.str, builtins.object) -> builtins.object, def [V] (builtins.str, V`4) -> builtins.object)" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictGetMethodTotalFalse] from typing import TypedDict, Literal class Unrelated: pass D = TypedDict('D', {'x': int, 'y': str}, total=False) d: D u: Unrelated x: Literal['x'] y: Literal['y'] z: Literal['z'] x_or_y: Literal['x', 'y'] x_or_z: Literal['x', 'z'] x_or_y_or_z: Literal['x', 'y', 'z'] # test with literal expression reveal_type(d.get('x')) # N: Revealed type is "builtins.int | None" reveal_type(d.get('y')) # N: Revealed type is "builtins.str | None" reveal_type(d.get('z')) # N: Revealed type is "builtins.object" reveal_type(d.get('x', u)) # N: Revealed type is "builtins.int | __main__.Unrelated" reveal_type(d.get('x', 1)) # N: Revealed type is "builtins.int" reveal_type(d.get('y', None)) # N: Revealed type is "builtins.str | None" # test with literal type / union of literal types with implicit default reveal_type(d.get(x)) # N: Revealed type is "builtins.int | None" reveal_type(d.get(y)) # N: Revealed type is "builtins.str | None" reveal_type(d.get(z)) # N: Revealed type is "builtins.object" reveal_type(d.get(x_or_y)) # N: Revealed type is "builtins.int | builtins.str | None" reveal_type(d.get(x_or_z)) # N: Revealed type is "builtins.object" reveal_type(d.get(x_or_y_or_z)) # N: Revealed type is "builtins.object" # test with literal type / union of literal types with explicit default reveal_type(d.get(x, u)) # N: Revealed type is "builtins.int | __main__.Unrelated" reveal_type(d.get(y, u)) # N: Revealed type is "builtins.str | __main__.Unrelated" reveal_type(d.get(z, u)) # N: Revealed type is "builtins.object" reveal_type(d.get(x_or_y, u)) # N: Revealed type is "builtins.int | builtins.str | __main__.Unrelated" reveal_type(d.get(x_or_z, u)) # N: Revealed type is "builtins.object" reveal_type(d.get(x_or_y_or_z, u)) # N: Revealed type is "builtins.object" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictGetMethodTotalTrue] from typing import TypedDict, Literal class Unrelated: pass D = TypedDict('D', {'x': int, 'y': str}, total=True) d: D u: Unrelated x: Literal['x'] y: Literal['y'] z: Literal['z'] x_or_y: Literal['x', 'y'] x_or_z: Literal['x', 'z'] x_or_y_or_z: Literal['x', 'y', 'z'] # test with literal expression reveal_type(d.get('x')) # N: Revealed type is "builtins.int" reveal_type(d.get('y')) # N: Revealed type is "builtins.str" reveal_type(d.get('z')) # N: Revealed type is "builtins.object" reveal_type(d.get('x', u)) # N: Revealed type is "builtins.int" reveal_type(d.get('x', 1)) # N: Revealed type is "builtins.int" reveal_type(d.get('y', None)) # N: Revealed type is "builtins.str" # test with literal type / union of literal types with implicit default reveal_type(d.get(x)) # N: Revealed type is "builtins.int" reveal_type(d.get(y)) # N: Revealed type is "builtins.str" reveal_type(d.get(z)) # N: Revealed type is "builtins.object" reveal_type(d.get(x_or_y)) # N: Revealed type is "builtins.int | builtins.str" reveal_type(d.get(x_or_z)) # N: Revealed type is "builtins.object" reveal_type(d.get(x_or_y_or_z)) # N: Revealed type is "builtins.object" # test with literal type / union of literal types with explicit default reveal_type(d.get(x, u)) # N: Revealed type is "builtins.int" reveal_type(d.get(y, u)) # N: Revealed type is "builtins.str" reveal_type(d.get(z, u)) # N: Revealed type is "builtins.object" reveal_type(d.get(x_or_y, u)) # N: Revealed type is "builtins.int | builtins.str" reveal_type(d.get(x_or_z, u)) # N: Revealed type is "builtins.object" reveal_type(d.get(x_or_y_or_z, u)) # N: Revealed type is "builtins.object" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictGetMethodTotalMixed] from typing import TypedDict, Literal from typing_extensions import Required, NotRequired class Unrelated: pass D = TypedDict('D', {'x': Required[int], 'y': NotRequired[str]}) d: D u: Unrelated x: Literal['x'] y: Literal['y'] z: Literal['z'] x_or_y: Literal['x', 'y'] x_or_z: Literal['x', 'z'] x_or_y_or_z: Literal['x', 'y', 'z'] # test with literal expression reveal_type(d.get('x')) # N: Revealed type is "builtins.int" reveal_type(d.get('y')) # N: Revealed type is "builtins.str | None" reveal_type(d.get('z')) # N: Revealed type is "builtins.object" reveal_type(d.get('x', u)) # N: Revealed type is "builtins.int" reveal_type(d.get('x', 1)) # N: Revealed type is "builtins.int" reveal_type(d.get('y', None)) # N: Revealed type is "builtins.str | None" # test with literal type / union of literal types with implicit default reveal_type(d.get(x)) # N: Revealed type is "builtins.int" reveal_type(d.get(y)) # N: Revealed type is "builtins.str | None" reveal_type(d.get(z)) # N: Revealed type is "builtins.object" reveal_type(d.get(x_or_y)) # N: Revealed type is "builtins.int | builtins.str | None" reveal_type(d.get(x_or_z)) # N: Revealed type is "builtins.object" reveal_type(d.get(x_or_y_or_z)) # N: Revealed type is "builtins.object" # test with literal type / union of literal types with explicit default reveal_type(d.get(x, u)) # N: Revealed type is "builtins.int" reveal_type(d.get(y, u)) # N: Revealed type is "builtins.str | __main__.Unrelated" reveal_type(d.get(z, u)) # N: Revealed type is "builtins.object" reveal_type(d.get(x_or_y, u)) # N: Revealed type is "builtins.int | builtins.str | __main__.Unrelated" reveal_type(d.get(x_or_z, u)) # N: Revealed type is "builtins.object" reveal_type(d.get(x_or_y_or_z, u)) # N: Revealed type is "builtins.object" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictGetMethodTypeContext] from typing import List, TypedDict class A: pass D = TypedDict('D', {'x': List[int], 'y': int}, total=False) d: D reveal_type(d.get('x', [])) # N: Revealed type is "builtins.list[builtins.int]" reveal_type(d.get('x', ['x'])) # N: Revealed type is "builtins.list[builtins.int] | builtins.list[builtins.str]" a = [''] reveal_type(d.get('x', a)) # N: Revealed type is "builtins.list[builtins.int] | builtins.list[builtins.str]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictGetMethodInvalidArgs] from typing import TypedDict D = TypedDict('D', {'x': int, 'y': str}) d: D d.get() # E: All overload variants of "get" of "Mapping" require at least one argument \ # N: Possible overload variants: \ # N: def get(self, str, /) -> object \ # N: def get(self, str, object, /) -> object \ # N: def [V] get(self, str, V, /) -> object d.get('x', 1, 2) # E: No overload variant of "get" of "Mapping" matches argument types "str", "int", "int" \ # N: Possible overload variants: \ # N: def get(self, str, /) -> object \ # N: def get(self, str, object, /) -> object \ # N: def [V] get(self, str, int | V, /) -> object x = d.get('z') reveal_type(x) # N: Revealed type is "builtins.object" s = '' y = d.get(s) reveal_type(y) # N: Revealed type is "builtins.object" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictMissingMethod] from typing import TypedDict D = TypedDict('D', {'x': int, 'y': str}) d: D d.bad(1) # E: "D" has no attribute "bad" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictChainedGetMethodWithDictFallback] from typing import TypedDict D = TypedDict('D', {'x': int, 'y': str}) E = TypedDict('E', {'d': D}) p = E(d=D(x=0, y='')) reveal_type(p.get('d', {'x': 1, 'y': ''})) # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictGetDefaultParameterStillTypeChecked] from typing import TypedDict TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int}) p = TaggedPoint(type='2d', x=42, y=1337) p.get('x', 1 + 'y') # E: Unsupported operand types for + ("int" and "str") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictChainedGetWithEmptyDictDefault] from typing import TypedDict C = TypedDict('C', {'a': int}, total=True) D = TypedDict('D', {'x': C, 'y': str}, total=False) d: D reveal_type(d.get('x', {})) # N: Revealed type is "TypedDict('__main__.C', {'a'?: builtins.int})" reveal_type(d.get('x', None)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int}) | None" reveal_type(d.get('x', {}).get('a')) # N: Revealed type is "builtins.int | None" reveal_type(d.get('x', {})['a']) # N: Revealed type is "builtins.int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictChainedGetWithEmptyDictDefault2] from typing import TypedDict C = TypedDict('C', {'a': int}, total=False) D = TypedDict('D', {'x': C, 'y': str}, total=True) d: D reveal_type(d.get('x', {})) # N: Revealed type is "TypedDict('__main__.C', {'a'?: builtins.int})" reveal_type(d.get('x', None)) # N: Revealed type is "TypedDict('__main__.C', {'a'?: builtins.int})" reveal_type(d.get('x', {}).get('a')) # N: Revealed type is "builtins.int | None" reveal_type(d.get('x', {})['a']) # N: Revealed type is "builtins.int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictChainedGetWithEmptyDictDefault3] from typing import TypedDict C = TypedDict('C', {'a': int}, total=True) D = TypedDict('D', {'x': C, 'y': str}, total=True) d: D reveal_type(d.get('x', {})) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int})" reveal_type(d.get('x', None)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int})" reveal_type(d.get('x', {}).get('a')) # N: Revealed type is "builtins.int" reveal_type(d.get('x', {})['a']) # N: Revealed type is "builtins.int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictChainedGetWithEmptyDictDefault4] from typing import TypedDict C = TypedDict('C', {'a': int}, total=False) D = TypedDict('D', {'x': C, 'y': str}, total=False) d: D reveal_type(d.get('x', {})) # N: Revealed type is "TypedDict('__main__.C', {'a'?: builtins.int})" reveal_type(d.get('x', None)) # N: Revealed type is "TypedDict('__main__.C', {'a'?: builtins.int}) | None" reveal_type(d.get('x', {}).get('a')) # N: Revealed type is "builtins.int | None" reveal_type(d.get('x', {})['a']) # N: Revealed type is "builtins.int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictGetMethodChained] # check that chaining with get like ``.get(key, {}).get(subkey, {})`` works. from typing import TypedDict, Mapping from typing_extensions import Required, NotRequired, Never class Total(TypedDict, total=True): # no keys optional key_one: int key_two: str class Maybe(TypedDict, total=False): # all keys are optional key_one: int key_two: str class Mixed(TypedDict): # some keys optional key_one: Required[int] key_two: NotRequired[str] class Config(TypedDict): required_total: Required[Total] optional_total: NotRequired[Total] required_mixed: Required[Mixed] optional_mixed: NotRequired[Mixed] required_maybe: Required[Maybe] optional_maybe: NotRequired[Maybe] def test_chaining(d: Config) -> None: reveal_type( d.get("required_total", {}) ) # N: Revealed type is "TypedDict('__main__.Total', {'key_one': builtins.int, 'key_two': builtins.str})" reveal_type( d.get("optional_total", {}) ) # N: Revealed type is "TypedDict('__main__.Total', {'key_one'?: builtins.int, 'key_two'?: builtins.str})" reveal_type( d.get("required_maybe", {}) ) # N: Revealed type is "TypedDict('__main__.Maybe', {'key_one'?: builtins.int, 'key_two'?: builtins.str})" reveal_type( d.get("optional_maybe", {}) ) # N: Revealed type is "TypedDict('__main__.Maybe', {'key_one'?: builtins.int, 'key_two'?: builtins.str})" reveal_type( d.get("required_mixed", {}) ) # N: Revealed type is "TypedDict('__main__.Mixed', {'key_one': builtins.int, 'key_two'?: builtins.str})" reveal_type( d.get("optional_mixed", {}) ) # N: Revealed type is "TypedDict('__main__.Mixed', {'key_one'?: builtins.int, 'key_two'?: builtins.str})" reveal_type( d.get("required_total", {}).get("key_one") ) # N: Revealed type is "builtins.int" reveal_type( d.get("required_total", {}).get("key_two") ) # N: Revealed type is "builtins.str" reveal_type( d.get("required_total", {}).get("bad_key") ) # N: Revealed type is "builtins.object" reveal_type( d.get("optional_total", {}).get("key_one") ) # N: Revealed type is "builtins.int | None" reveal_type( d.get("optional_total", {}).get("key_two") ) # N: Revealed type is "builtins.str | None" reveal_type( d.get("optional_total", {}).get("bad_key") ) # N: Revealed type is "builtins.object" reveal_type( d.get("required_maybe", {}).get("key_one") ) # N: Revealed type is "builtins.int | None" reveal_type( d.get("required_maybe", {}).get("key_two") ) # N: Revealed type is "builtins.str | None" reveal_type( d.get("required_maybe", {}).get("bad_key") ) # N: Revealed type is "builtins.object" reveal_type( d.get("optional_maybe", {}).get("key_one") ) # N: Revealed type is "builtins.int | None" reveal_type( d.get("optional_maybe", {}).get("key_two") ) # N: Revealed type is "builtins.str | None" reveal_type( d.get("optional_maybe", {}).get("bad_key") ) # N: Revealed type is "builtins.object" reveal_type( d.get("required_mixed", {}).get("key_one") ) # N: Revealed type is "builtins.int" reveal_type( d.get("required_mixed", {}).get("key_two") ) # N: Revealed type is "builtins.str | None" reveal_type( d.get("required_mixed", {}).get("bad_key") ) # N: Revealed type is "builtins.object" reveal_type( d.get("optional_mixed", {}).get("key_one") ) # N: Revealed type is "builtins.int | None" reveal_type( d.get("optional_mixed", {}).get("key_two") ) # N: Revealed type is "builtins.str | None" reveal_type( d.get("optional_mixed", {}).get("bad_key") ) # N: Revealed type is "builtins.object" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictGetWithNestedUnionOfTypedDicts] # https://github.com/python/mypy/issues/19902 from typing import TypedDict, Union from typing_extensions import TypeAlias, NotRequired class A(TypedDict): key: NotRequired[int] class B(TypedDict): key: NotRequired[int] class C(TypedDict): key: NotRequired[int] A_or_B: TypeAlias = Union[A, B] A_or_B_or_C: TypeAlias = Union[A_or_B, C] def test(d: A_or_B_or_C) -> None: reveal_type(d.get("key")) # N: Revealed type is "builtins.int | None" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Totality (the "total" keyword argument) [case testTypedDictWithTotalTrue] from typing import TypedDict D = TypedDict('D', {'x': int, 'y': str}, total=True) d: D reveal_type(d) \ # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictWithInvalidTotalArgument] from typing import TypedDict A = TypedDict('A', {'x': int}, total=0) # E: "total" argument must be a True or False literal B = TypedDict('B', {'x': int}, total=bool) # E: "total" argument must be a True or False literal C = TypedDict('C', {'x': int}, x=False) # E: Unexpected keyword argument "x" for "TypedDict" D = TypedDict('D', {'x': int}, False) # E: Unexpected arguments to TypedDict() E = TypedDict('E', {'x': int}, total=False, x=False) # E: Unexpected keyword argument "x" for "TypedDict" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictWithTotalFalse] from typing import TypedDict D = TypedDict('D', {'x': int, 'y': str}, total=False) def f(d: D) -> None: reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})" f({}) f({'x': 1}) f({'y': ''}) f({'x': 1, 'y': ''}) f({'x': 1, 'z': ''}) # E: Extra key "z" for TypedDict "D" f({'x': ''}) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictConstructorWithTotalFalse] from typing import TypedDict D = TypedDict('D', {'x': int, 'y': str}, total=False) def f(d: D) -> None: pass reveal_type(D()) # N: Revealed type is "TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})" reveal_type(D(x=1)) # N: Revealed type is "TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})" f(D(y='')) f(D(x=1, y='')) f(D(x=1, z='')) # E: Extra key "z" for TypedDict "D" f(D(x='')) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictIndexingWithNonRequiredKey] from typing import TypedDict D = TypedDict('D', {'x': int, 'y': str}, total=False) d: D reveal_type(d['x']) # N: Revealed type is "builtins.int" reveal_type(d['y']) # N: Revealed type is "builtins.str" reveal_type(d.get('x')) # N: Revealed type is "builtins.int | None" reveal_type(d.get('y')) # N: Revealed type is "builtins.str | None" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictSubtypingWithTotalFalse] from typing import TypedDict A = TypedDict('A', {'x': int}) B = TypedDict('B', {'x': int}, total=False) C = TypedDict('C', {'x': int, 'y': str}, total=False) def fa(a: A) -> None: pass def fb(b: B) -> None: pass def fc(c: C) -> None: pass a: A b: B c: C fb(b) fc(c) fb(c) fb(a) # E: Argument 1 to "fb" has incompatible type "A"; expected "B" fa(b) # E: Argument 1 to "fa" has incompatible type "B"; expected "A" fc(b) # E: Argument 1 to "fc" has incompatible type "B"; expected "C" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictJoinWithTotalFalse] from typing import TypedDict, TypeVar A = TypedDict('A', {'x': int}) B = TypedDict('B', {'x': int}, total=False) C = TypedDict('C', {'x': int, 'y': str}, total=False) T = TypeVar('T') def j(x: T, y: T) -> T: return x a: A b: B c: C reveal_type(j(a, b)) \ # N: Revealed type is "TypedDict({'x'?=: builtins.int})" reveal_type(j(b, b)) \ # N: Revealed type is "TypedDict({'x'?: builtins.int})" reveal_type(j(c, c)) \ # N: Revealed type is "TypedDict({'x'?: builtins.int, 'y'?: builtins.str})" reveal_type(j(b, c)) \ # N: Revealed type is "TypedDict({'x'?: builtins.int})" reveal_type(j(c, b)) \ # N: Revealed type is "TypedDict({'x'?: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictClassWithTotalArgument] from typing import TypedDict class D(TypedDict, total=False): x: int y: str d: D reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictClassWithInvalidTotalArgument] from typing import TypedDict class D(TypedDict, total=1): # E: "total" argument must be a True or False literal x: int class E(TypedDict, total=bool): # E: "total" argument must be a True or False literal x: int class F(TypedDict, total=xyz): # E: Name "xyz" is not defined \ # E: "total" argument must be a True or False literal x: int [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictClassInheritanceWithTotalArgument] from typing import TypedDict class A(TypedDict): x: int class B(TypedDict, A, total=False): y: int class C(TypedDict, B, total=True): z: str c: C reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'x': builtins.int, 'y'?: builtins.int, 'z': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testNonTotalTypedDictInErrorMessages] from typing import TypedDict A = TypedDict('A', {'x': int, 'y': str}, total=False) B = TypedDict('B', {'x': int, 'z': str, 'a': int}, total=False) C = TypedDict('C', {'x': int, 'z': str, 'a': str}, total=False) a: A b: B c: C def f(a: A) -> None: pass l = [a, b] # Join generates an anonymous TypedDict f(l) # E: Argument 1 to "f" has incompatible type "list[TypedDict({'x'?: int})]"; expected "A" ll = [b, c] f(ll) # E: Argument 1 to "f" has incompatible type "list[TypedDict({'x'?: int, 'z'?: str, 'a'?=: object})]"; expected "A" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testNonTotalTypedDictCanBeEmpty] # flags: --warn-unreachable from typing import TypedDict class A(TypedDict): ... class B(TypedDict, total=False): x: int a: A = {} b: B = {} if not a: reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {})" if not b: reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'x'?: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Create Type (Errors) [case testCannotCreateTypedDictTypeWithTooFewArguments] from typing import TypedDict Point = TypedDict('Point') # E: Too few arguments for TypedDict() [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictTypeWithTooManyArguments] from typing import TypedDict Point = TypedDict('Point', {'x': int, 'y': int}, dict) # E: Unexpected arguments to TypedDict() [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictTypeWithInvalidName] from typing import TypedDict Point = TypedDict(dict, {'x': int, 'y': int}) # E: TypedDict() expects a string literal as the first argument [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictTypeWithInvalidItems] from typing import TypedDict Point = TypedDict('Point', {'x'}) # E: TypedDict() expects a dictionary literal as the second argument [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictTypeWithKwargs] from typing import TypedDict d = {'x': int, 'y': int} Point = TypedDict('Point', {**d}) # E: Invalid TypedDict() field name [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictTypeWithBytes] from typing import TypedDict Point = TypedDict(b'Point', {'x': int, 'y': int}) # E: TypedDict() expects a string literal as the first argument # This technically works at runtime but doesn't make sense. Point2 = TypedDict('Point2', {b'x': int}) # E: Invalid TypedDict() field name [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- NOTE: The following code works at runtime but is not yet supported by mypy. -- Keyword arguments may potentially be supported in the future. [case testCannotCreateTypedDictTypeWithNonpositionalArgs] from typing import TypedDict Point = TypedDict(typename='Point', fields={'x': int, 'y': int}) # E: Unexpected arguments to TypedDict() [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictTypeWithInvalidItemName] from typing import TypedDict Point = TypedDict('Point', {int: int, int: int}) # E: Invalid TypedDict() field name [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictTypeWithInvalidItemType] from typing import TypedDict Point = TypedDict('Point', {'x': 1, 'y': 1}) # E: Invalid type: try using Literal[1] instead? [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCannotCreateTypedDictTypeWithInvalidName2] from typing import TypedDict X = TypedDict('Y', {'x': int}) # E: First argument "Y" to TypedDict() does not match variable name "X" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Overloading [case testTypedDictOverloading] from typing import overload, Iterable, TypedDict A = TypedDict('A', {'x': int}) @overload def f(x: Iterable[str]) -> str: ... @overload def f(x: int) -> int: ... def f(x): pass a: A reveal_type(f(a)) # N: Revealed type is "builtins.str" reveal_type(f(1)) # N: Revealed type is "builtins.int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverloading2] from typing import overload, Iterable, TypedDict A = TypedDict('A', {'x': int}) @overload def f(x: Iterable[int]) -> None: ... @overload def f(x: int) -> None: ... def f(x): pass a: A f(a) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [out] main:12: error: Argument 1 to "f" has incompatible type "A"; expected "Iterable[int]" main:12: note: Following member(s) of "A" have conflicts: main:12: note: Expected: main:12: note: def __iter__(self) -> Iterator[int] main:12: note: Got: main:12: note: def __iter__(self) -> Iterator[str] [case testTypedDictOverloading3] from typing import TypedDict, overload A = TypedDict('A', {'x': int}) @overload def f(x: str) -> None: ... @overload def f(x: int) -> None: ... def f(x): pass a: A f(a) # E: No overload variant of "f" matches argument type "A" \ # N: Possible overload variants: \ # N: def f(x: str) -> None \ # N: def f(x: int) -> None [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverloading4] from typing import TypedDict, overload A = TypedDict('A', {'x': int}) B = TypedDict('B', {'x': str}) @overload def f(x: A) -> int: ... @overload def f(x: int) -> str: ... def f(x): pass a: A b: B reveal_type(f(a)) # N: Revealed type is "builtins.int" reveal_type(f(1)) # N: Revealed type is "builtins.str" f(b) # E: Argument 1 to "f" has incompatible type "B"; expected "A" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverloading5] from typing import TypedDict, overload A = TypedDict('A', {'x': int}) B = TypedDict('B', {'y': str}) C = TypedDict('C', {'y': int}) @overload def f(x: A) -> None: ... @overload def f(x: B) -> None: ... def f(x): pass a: A b: B c: C f(a) f(b) f(c) # E: Argument 1 to "f" has incompatible type "C"; expected "A" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverloading6] from typing import TypedDict, overload A = TypedDict('A', {'x': int}) B = TypedDict('B', {'y': str}) @overload def f(x: A) -> int: ... @overload def f(x: B) -> str: ... def f(x): pass a: A b: B reveal_type(f(a)) # N: Revealed type is "builtins.int" reveal_type(f(b)) # N: Revealed type is "builtins.str" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] -- Special cases [case testForwardReferenceInTypedDict] from typing import TypedDict, Mapping X = TypedDict('X', {'b': 'B', 'c': 'C'}) class B: pass class C(B): pass x: X reveal_type(x) # N: Revealed type is "TypedDict('__main__.X', {'b': __main__.B, 'c': __main__.C})" m1: Mapping[str, object] = x m2: Mapping[str, B] = x # E: Incompatible types in assignment (expression has type "X", variable has type "Mapping[str, B]") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testForwardReferenceInClassTypedDict] from typing import TypedDict, Mapping class X(TypedDict): b: 'B' c: 'C' class B: pass class C(B): pass x: X reveal_type(x) # N: Revealed type is "TypedDict('__main__.X', {'b': __main__.B, 'c': __main__.C})" m1: Mapping[str, object] = x m2: Mapping[str, B] = x # E: Incompatible types in assignment (expression has type "X", variable has type "Mapping[str, B]") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testForwardReferenceToTypedDictInTypedDict] from typing import TypedDict, Mapping X = TypedDict('X', {'a': 'A'}) A = TypedDict('A', {'b': int}) x: X reveal_type(x) # N: Revealed type is "TypedDict('__main__.X', {'a': TypedDict('__main__.A', {'b': builtins.int})})" reveal_type(x['a']['b']) # N: Revealed type is "builtins.int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testForwardReferenceInOverwrittenKey] from typing import ReadOnly, TypedDict class X("XB"): pass class Y("YB"): pass class Z("ZB"): pass class A(TypedDict): key: "X" class B(A): key: "Y" # E: Definition of field "key" incompatible with base class "A" class C(A): key: "Z" # E: Definition of field "key" incompatible with base class "A" class D(A): key: int # E: Definition of field "key" incompatible with base class "A" class XB: pass class YB(X): pass class ZB: pass [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testSelfRecursiveTypedDictInheriting] from typing import TypedDict def test() -> None: class MovieBase(TypedDict): name: str year: int class Movie(MovieBase): director: 'Movie' # E: Cannot resolve name "Movie" (possible cyclic definition) \ # N: Recursive types are not allowed at function scope m: Movie reveal_type(m['director']['name']) # N: Revealed type is "Any" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testSubclassOfRecursiveTypedDict] from typing import List, TypedDict def test() -> None: class Command(TypedDict): subcommands: List['Command'] # E: Cannot resolve name "Command" (possible cyclic definition) \ # N: Recursive types are not allowed at function scope class HelpCommand(Command): pass hc = HelpCommand(subcommands=[]) reveal_type(hc) # N: Revealed type is "TypedDict('__main__.HelpCommand@7', {'subcommands': builtins.list[Any]})" [builtins fixtures/list.pyi] [typing fixtures/typing-typeddict.pyi] [out] [case testTypedDictForwardAsUpperBound] from typing import TypedDict, TypeVar, Generic T = TypeVar('T', bound='M') class G(Generic[T]): x: T yb: G[int] # E: Type argument "int" of "G" must be a subtype of "M" yg: G[M] z: int = G[M]().x['x'] # type: ignore[used-before-def] class M(TypedDict): x: int [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [out] [case testTypedDictWithImportCycleForward] import a [file a.py] from typing import TypedDict from b import f N = TypedDict('N', {'a': str}) [file b.py] import a def f(x: a.N) -> None: reveal_type(x) reveal_type(x['a']) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [out] tmp/b.py:4: note: Revealed type is "TypedDict('a.N', {'a': builtins.str})" tmp/b.py:5: note: Revealed type is "builtins.str" [case testTypedDictImportCycle] import b [file a.py] class C: pass from b import tp x: tp reveal_type(x['x']) # N: Revealed type is "builtins.int" reveal_type(tp) # N: Revealed type is "def (*, x: builtins.int) -> TypedDict('b.tp', {'x': builtins.int})" tp(x='no') # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") [file b.py] from a import C from typing import TypedDict tp = TypedDict('tp', {'x': int}) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [out] [case testTypedDictAsStarStarArg] from typing import TypedDict A = TypedDict('A', {'x': int, 'y': str}) class B: pass def f1(x: int, y: str) -> None: ... def f2(x: int, y: int) -> None: ... def f3(x: B, y: str) -> None: ... def f4(x: int) -> None: pass def f5(x: int, y: str, z: int) -> None: pass def f6(x: int, z: str) -> None: pass a: A f1(**a) f2(**a) # E: Argument "y" to "f2" has incompatible type "str"; expected "int" f3(**a) # E: Argument "x" to "f3" has incompatible type "int"; expected "B" f4(**a) # E: Extra argument "y" from **args for "f4" f5(**a) # E: Missing positional arguments "y", "z" in call to "f5" f6(**a) # E: Extra argument "y" from **args for "f6" f1(1, **a) # E: "f1" gets multiple values for keyword argument "x" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAsStarStarArgConstraints] from typing import TypedDict, TypeVar, Union T = TypeVar('T') S = TypeVar('S') def f1(x: T, y: S) -> Union[T, S]: ... A = TypedDict('A', {'y': int, 'x': str}) a: A reveal_type(f1(**a)) # N: Revealed type is "builtins.str | builtins.int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAsStarStarArgCalleeKwargs] from typing import TypedDict A = TypedDict('A', {'x': int, 'y': str}) B = TypedDict('B', {'x': str, 'y': str}) def f(**kwargs: str) -> None: ... def g(x: int, **kwargs: str) -> None: ... a: A b: B f(**a) # E: Argument 1 to "f" has incompatible type "**A"; expected "str" f(**b) g(**a) g(**b) # E: Argument "x" to "g" has incompatible type "str"; expected "int" g(1, **a) # E: "g" gets multiple values for keyword argument "x" g(1, **b) # E: "g" gets multiple values for keyword argument "x" \ # E: Argument "x" to "g" has incompatible type "str"; expected "int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAsStarStarTwice] from typing import TypedDict A = TypedDict('A', {'x': int, 'y': str}) B = TypedDict('B', {'z': bytes}) C = TypedDict('C', {'x': str, 'z': bytes}) def f1(x: int, y: str, z: bytes) -> None: ... def f2(x: int, y: float, z: bytes) -> None: ... def f3(x: int, y: str, z: float) -> None: ... a: A b: B c: C f1(**a, **b) f1(**b, **a) f2(**a, **b) # E: Argument "y" to "f2" has incompatible type "str"; expected "float" f3(**a, **b) # E: Argument "z" to "f3" has incompatible type "bytes"; expected "float" f3(**b, **a) # E: Argument "z" to "f3" has incompatible type "bytes"; expected "float" f1(**a, **c) # E: "f1" gets multiple values for keyword argument "x" \ # E: Argument "x" to "f1" has incompatible type "str"; expected "int" f1(**c, **a) # E: "f1" gets multiple values for keyword argument "x" \ # E: Argument "x" to "f1" has incompatible type "str"; expected "int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAsStarStarAndDictAsStarStar] from typing import Any, Dict, TypedDict TD = TypedDict('TD', {'x': int, 'y': str}) def f1(x: int, y: str, z: bytes) -> None: ... def f2(x: int, y: str) -> None: ... td: TD d: Dict[Any, Any] f1(**td, **d) f1(**d, **td) f2(**td, **d) f2(**d, **td) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictNonMappingMethods] from typing import List, TypedDict A = TypedDict('A', {'x': int, 'y': List[int]}) a: A reveal_type(a.copy()) # N: Revealed type is "TypedDict('__main__.A', {'x': builtins.int, 'y': builtins.list[builtins.int]})" a.has_key('x') # E: "A" has no attribute "has_key" # TODO: Better error message a.clear() # E: "A" has no attribute "clear" a.setdefault('invalid', 1) # E: TypedDict "A" has no key "invalid" reveal_type(a.setdefault('x', 1)) # N: Revealed type is "builtins.int" reveal_type(a.setdefault('y', [])) # N: Revealed type is "builtins.list[builtins.int]" a.setdefault('y', '') # E: Argument 2 to "setdefault" of "TypedDict" has incompatible type "str"; expected "list[int]" x = '' a.setdefault(x, 1) # E: Expected TypedDict key to be string literal alias = a.setdefault alias(x, 1) # E: Argument 1 has incompatible type "str"; expected "Never" a.update({}) a.update({'x': 1}) a.update({'x': ''}) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") a.update({'x': 1, 'y': []}) a.update({'x': 1, 'y': [1]}) a.update({'z': 1}) # E: Unexpected TypedDict key "z" a.update({'z': 1, 'zz': 1}) # E: Unexpected TypedDict keys ("z", "zz") a.update({'z': 1, 'x': 1}) # E: Expected TypedDict key "x" but found keys ("z", "x") d = {'x': 1} a.update(d) # E: Argument 1 to "update" of "TypedDict" has incompatible type "dict[str, int]"; expected "TypedDict({'x'?: int, 'y'?: list[int]})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictPopMethod] from typing import List, TypedDict A = TypedDict('A', {'x': int, 'y': List[int]}, total=False) B = TypedDict('B', {'x': int}) a: A b: B reveal_type(a.pop('x')) # N: Revealed type is "builtins.int" reveal_type(a.pop('y', [])) # N: Revealed type is "builtins.list[builtins.int]" reveal_type(a.pop('x', '')) # N: Revealed type is "builtins.int | Literal['']?" reveal_type(a.pop('x', (1, 2))) # N: Revealed type is "builtins.int | tuple[Literal[1]?, Literal[2]?]" a.pop('invalid', '') # E: TypedDict "A" has no key "invalid" b.pop('x') # E: Key "x" of TypedDict "B" cannot be deleted x = '' b.pop(x) # E: Expected TypedDict key to be string literal pop = b.pop pop('x') # E: Argument 1 has incompatible type "str"; expected "Never" pop('invalid') # E: Argument 1 has incompatible type "str"; expected "Never" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictDel] from typing import List, TypedDict A = TypedDict('A', {'x': int, 'y': List[int]}, total=False) B = TypedDict('B', {'x': int}) a: A b: B del a['x'] del a['invalid'] # E: TypedDict "A" has no key "invalid" del b['x'] # E: Key "x" of TypedDict "B" cannot be deleted s = '' del a[s] # E: Expected TypedDict key to be string literal del b[s] # E: Expected TypedDict key to be string literal alias = b.__delitem__ alias('x') alias(s) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testPluginUnionsOfTypedDicts] from typing import TypedDict, Union class TDA(TypedDict): a: int b: str class TDB(TypedDict): a: int b: int c: int td: Union[TDA, TDB] reveal_type(td.get('a')) # N: Revealed type is "builtins.int" reveal_type(td.get('b')) # N: Revealed type is "builtins.str | builtins.int" reveal_type(td.get('c')) # N: Revealed type is "builtins.object" reveal_type(td['a']) # N: Revealed type is "builtins.int" reveal_type(td['b']) # N: Revealed type is "builtins.str | builtins.int" reveal_type(td['c']) # N: Revealed type is "Any | builtins.int" \ # E: TypedDict "TDA" has no key "c" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testPluginUnionsOfTypedDictsNonTotal] from typing import TypedDict, Union class TDA(TypedDict, total=False): a: int b: str class TDB(TypedDict, total=False): a: int b: int c: int td: Union[TDA, TDB] reveal_type(td.pop('a')) # N: Revealed type is "builtins.int" reveal_type(td.pop('b')) # N: Revealed type is "builtins.str | builtins.int" reveal_type(td.pop('c')) # N: Revealed type is "Any | builtins.int" \ # E: TypedDict "TDA" has no key "c" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithTypingExtensions] from typing_extensions import TypedDict class Point(TypedDict): x: int y: int p = Point(x=42, y=1337) reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateTypedDictWithTypingProper] from typing import TypedDict class Point(TypedDict): x: int y: int p = Point(x=42, y=1337) reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOptionalUpdate] from typing import TypedDict, Union class A(TypedDict): x: int d: A d.update({'x': 1}) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverlapWithDict] # mypy: strict-equality from typing import TypedDict, Dict class Config(TypedDict): a: str b: str x: Dict[str, str] y: Config x == y [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverlapWithDictNonOverlapping] # mypy: strict-equality from typing import TypedDict, Dict class Config(TypedDict): a: str b: int x: Dict[str, str] y: Config x == y # E: Non-overlapping equality check (left operand type: "dict[str, str]", right operand type: "Config") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverlapWithDictNonTotal] # mypy: strict-equality from typing import TypedDict, Dict class Config(TypedDict, total=False): a: str b: int x: Dict[str, str] y: Config x == y [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverlapWithDictNonTotalNonOverlapping] # mypy: strict-equality from typing import TypedDict, Dict class Config(TypedDict, total=False): a: int b: int x: Dict[str, str] y: Config x == y # E: Non-overlapping equality check (left operand type: "dict[str, str]", right operand type: "Config") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverlapWithDictEmpty] # mypy: strict-equality from typing import TypedDict class Config(TypedDict): a: str b: str x: Config x == {} # E: Non-overlapping equality check (left operand type: "Config", right operand type: "dict[Never, Never]") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverlapWithDictNonTotalEmpty] # mypy: strict-equality from typing import TypedDict class Config(TypedDict, total=False): a: str b: str x: Config x == {} [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverlapWithDictNonStrKey] # mypy: strict-equality from typing import TypedDict, Dict, Union class Config(TypedDict): a: str b: str x: Config y: Dict[Union[str, int], str] x == y [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverlapWithDictOverload] from typing import overload, TypedDict, Dict class Map(TypedDict): x: int y: str @overload def func(x: Map) -> int: ... @overload def func(x: Dict[str, str]) -> str: ... def func(x): pass [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverlapWithDictOverloadBad] from typing import overload, TypedDict, Dict class Map(TypedDict, total=False): x: int y: str @overload def func(x: Map) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types @overload def func(x: Dict[str, str]) -> str: ... def func(x): pass [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverlapWithDictOverloadMappingBad] from typing import overload, TypedDict, Mapping class Map(TypedDict, total=False): x: int y: str @overload def func(x: Map) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types @overload def func(x: Mapping[str, str]) -> str: ... def func(x): pass [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictOverlapWithDictOverloadNonStrKey] from typing import overload, TypedDict, Dict class Map(TypedDict): x: str y: str @overload def func(x: Map) -> int: ... @overload def func(x: Dict[int, str]) -> str: ... def func(x): pass [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictIsInstance] from typing import TypedDict, Union class User(TypedDict): id: int name: str u: Union[str, User] u2: User if isinstance(u, dict): reveal_type(u) # N: Revealed type is "TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})" else: reveal_type(u) # N: Revealed type is "builtins.str" assert isinstance(u2, dict) reveal_type(u2) # N: Revealed type is "TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictIsInstanceABCs] from typing import TypedDict, Union, Mapping, Iterable class User(TypedDict): id: int name: str u: Union[int, User] u2: User if isinstance(u, Iterable): reveal_type(u) # N: Revealed type is "TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})" else: reveal_type(u) # N: Revealed type is "builtins.int" assert isinstance(u2, Mapping) reveal_type(u2) # N: Revealed type is "TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testTypedDictLiteralTypeKeyInCreation] from typing import TypedDict, Final, Literal class Value(TypedDict): num: int num: Final = 'num' v: Value = {num: 5} v = {num: ''} # E: Incompatible types (expression has type "str", TypedDict item "num" has type "int") bad: Final = 2 v = {bad: 3} # E: Expected TypedDict key to be string literal union: Literal['num', 'foo'] v = {union: 2} # E: Expected TypedDict key to be string literal num2: Literal['num'] v = {num2: 2} bad2: Literal['bad'] v = {bad2: 2} # E: Missing key "num" for TypedDict "Value" \ # E: Extra key "bad" for TypedDict "Value" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testOperatorContainsNarrowsTypedDicts_unionWithList] from __future__ import annotations from typing import assert_type, TypedDict, Union class D(TypedDict): foo: int d_or_list: D | list[str] if 'foo' in d_or_list: assert_type(d_or_list, Union[D, list[str]]) elif 'bar' in d_or_list: assert_type(d_or_list, list[str]) else: assert_type(d_or_list, list[str]) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_unionWithList_final] from __future__ import annotations from typing import assert_type, final, TypedDict, Union @final class D(TypedDict): foo: int d_or_list: D | list[str] if 'foo' in d_or_list: assert_type(d_or_list, Union[D, list[str]]) elif 'bar' in d_or_list: assert_type(d_or_list, list[str]) else: assert_type(d_or_list, list[str]) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_total_never] from __future__ import annotations from typing import assert_type, final, Literal, TypedDict, TypeVar, Union from typing_extensions import Never, NotRequired class D1(TypedDict): foo: int bar: NotRequired[Never] invalid: NotRequired[Never] class D2(TypedDict): foo: NotRequired[Never] bar: int invalid: NotRequired[Never] d: D1 | D2 if 'foo' in d: assert_type(d, D1) else: assert_type(d, D2) foo_or_bar: Literal['foo', 'bar'] if foo_or_bar in d: assert_type(d, Union[D1, D2]) else: assert_type(d, Union[D1, D2]) foo_or_invalid: Literal['foo', 'invalid'] if foo_or_invalid in d: assert_type(d, D1) # won't narrow 'foo_or_invalid' assert_type(foo_or_invalid, Literal['foo', 'invalid']) else: assert_type(d, Union[D1, D2]) # won't narrow 'foo_or_invalid' assert_type(foo_or_invalid, Literal['foo', 'invalid']) TD = TypeVar('TD', D1, D2) def f(arg: TD) -> None: value: int if 'foo' in arg: assert_type(arg['foo'], int) else: assert_type(arg['bar'], int) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_total_final] from __future__ import annotations from typing import assert_type, final, Literal, TypedDict, TypeVar, Union @final class D1(TypedDict): foo: int @final class D2(TypedDict): bar: int d: D1 | D2 if 'foo' in d: assert_type(d, D1) else: assert_type(d, D2) foo_or_bar: Literal['foo', 'bar'] if foo_or_bar in d: assert_type(d, Union[D1, D2]) else: assert_type(d, Union[D1, D2]) foo_or_invalid: Literal['foo', 'invalid'] if foo_or_invalid in d: assert_type(d, D1) # won't narrow 'foo_or_invalid' assert_type(foo_or_invalid, Literal['foo', 'invalid']) else: assert_type(d, Union[D1, D2]) # won't narrow 'foo_or_invalid' assert_type(foo_or_invalid, Literal['foo', 'invalid']) TD = TypeVar('TD', D1, D2) def f(arg: TD) -> None: value: int if 'foo' in arg: assert_type(arg['foo'], int) else: assert_type(arg['bar'], int) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_never] # flags: --warn-unreachable from __future__ import annotations from typing import assert_type, TypedDict, Union from typing_extensions import Never, NotRequired class DFooNotBar(TypedDict): foo: int bar: NotRequired[Never] class DBar(TypedDict): bar: int d_bar: DBar if 'bar' in d_bar: assert_type(d_bar, DBar) else: spam = 'ham' # E: Statement is unreachable if 'spam' in d_bar: assert_type(d_bar, DBar) else: assert_type(d_bar, DBar) d_foo_not_bar: DFooNotBar if 'spam' in d_foo_not_bar: spam = 'ham' else: assert_type(d_foo_not_bar, DFooNotBar) d_union: DFooNotBar | DBar if 'foo' in d_union: assert_type(d_union, Union[DFooNotBar, DBar]) else: assert_type(d_union, DBar) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_final] # flags: --warn-unreachable from __future__ import annotations from typing import assert_type, final, TypedDict, Union @final class DFinal(TypedDict): foo: int class DNotFinal(TypedDict): bar: int d_not_final: DNotFinal if 'bar' in d_not_final: assert_type(d_not_final, DNotFinal) else: spam = 'ham' # E: Statement is unreachable if 'spam' in d_not_final: assert_type(d_not_final, DNotFinal) else: assert_type(d_not_final, DNotFinal) d_final: DFinal if 'spam' in d_final: spam = 'ham' # E: Statement is unreachable else: assert_type(d_final, DFinal) d_union: DFinal | DNotFinal if 'foo' in d_union: assert_type(d_union, Union[DFinal, DNotFinal]) else: assert_type(d_union, DNotFinal) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_partialThroughTotalFalse_never] from __future__ import annotations from typing import assert_type, Literal, TypedDict, Union from typing_extensions import Never, NotRequired class DTotal(TypedDict): required_key: int optional_key: NotRequired[Never] class DNotTotal(TypedDict, total=False): required_key: Never optional_key: int d: DTotal | DNotTotal if 'required_key' in d: assert_type(d, DTotal) else: assert_type(d, DNotTotal) if 'optional_key' in d: assert_type(d, DNotTotal) else: assert_type(d, Union[DTotal, DNotTotal]) key: Literal['optional_key', 'required_key'] if key in d: assert_type(d, Union[DTotal, DNotTotal]) else: assert_type(d, Union[DTotal, DNotTotal]) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_partialThroughTotalFalse_final] from __future__ import annotations from typing import assert_type, final, Literal, TypedDict, Union @final class DTotal(TypedDict): required_key: int @final class DNotTotal(TypedDict, total=False): optional_key: int d: DTotal | DNotTotal if 'required_key' in d: assert_type(d, DTotal) else: assert_type(d, DNotTotal) if 'optional_key' in d: assert_type(d, DNotTotal) else: assert_type(d, Union[DTotal, DNotTotal]) key: Literal['optional_key', 'required_key'] if key in d: assert_type(d, Union[DTotal, DNotTotal]) else: assert_type(d, Union[DTotal, DNotTotal]) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_partialThroughNotRequired_never] from __future__ import annotations from typing import assert_type, final, TypedDict, Union from typing_extensions import Never, Required, NotRequired class D1(TypedDict): required_key: Required[int] optional_key: NotRequired[int] class D2(TypedDict): abc: int xyz: int required_key: NotRequired[Never] optional_key: NotRequired[Never] d: D1 | D2 if 'required_key' in d: assert_type(d, D1) else: assert_type(d, D2) if 'optional_key' in d: assert_type(d, D1) else: assert_type(d, Union[D1, D2]) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_partialThroughNotRequired_final] from __future__ import annotations from typing import assert_type, final, TypedDict, Union from typing_extensions import Required, NotRequired @final class D1(TypedDict): required_key: Required[int] optional_key: NotRequired[int] @final class D2(TypedDict): abc: int xyz: int d: D1 | D2 if 'required_key' in d: assert_type(d, D1) else: assert_type(d, D2) if 'optional_key' in d: assert_type(d, D1) else: assert_type(d, Union[D1, D2]) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testCannotSubclassFinalTypedDict] from typing import TypedDict, final @final class DummyTypedDict(TypedDict): int_val: int float_val: float str_val: str class SubType(DummyTypedDict): # E: Cannot inherit from final class "DummyTypedDict" pass [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testCannotSubclassFinalTypedDictWithForwardDeclarations] from typing import TypedDict, final @final class DummyTypedDict(TypedDict): forward_declared: "ForwardDeclared" class SubType(DummyTypedDict): # E: Cannot inherit from final class "DummyTypedDict" pass class ForwardDeclared: pass [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testTypedDictCannotBeDisjointBase] from typing import TypedDict from typing_extensions import disjoint_base @disjoint_base # E: @disjoint_base cannot be used with TypedDict class A(TypedDict): pass [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictTypeNarrowingWithFinalKey] from typing import Final, Optional, TypedDict KEY_NAME: Final = "bar" class Foo(TypedDict): bar: Optional[str] foo = Foo(bar="hello") if foo["bar"] is not None: reveal_type(foo["bar"]) # N: Revealed type is "builtins.str" reveal_type(foo[KEY_NAME]) # N: Revealed type is "builtins.str" if foo[KEY_NAME] is not None: reveal_type(foo["bar"]) # N: Revealed type is "builtins.str" reveal_type(foo[KEY_NAME]) # N: Revealed type is "builtins.str" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictDoubleForwardClass] from typing import Any, List, TypedDict class Foo(TypedDict): bar: Bar baz: Bar Bar = List[Any] foo: Foo reveal_type(foo['bar']) # N: Revealed type is "builtins.list[Any]" reveal_type(foo['baz']) # N: Revealed type is "builtins.list[Any]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictDoubleForwardFunc] from typing import Any, List, TypedDict Foo = TypedDict('Foo', {'bar': 'Bar', 'baz': 'Bar'}) Bar = List[Any] foo: Foo reveal_type(foo['bar']) # N: Revealed type is "builtins.list[Any]" reveal_type(foo['baz']) # N: Revealed type is "builtins.list[Any]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictDoubleForwardMixed] from typing import Any, List, TypedDict Bar = List[Any] class Foo(TypedDict): foo: Toto bar: Bar baz: Bar Toto = int foo: Foo reveal_type(foo['foo']) # N: Revealed type is "builtins.int" reveal_type(foo['bar']) # N: Revealed type is "builtins.list[Any]" reveal_type(foo['baz']) # N: Revealed type is "builtins.list[Any]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testAssignTypedDictAsAttribute] from typing import TypedDict class A: def __init__(self) -> None: self.b = TypedDict('b', {'x': int, 'y': str}) # E: TypedDict type as attribute is not supported reveal_type(A().b) # N: Revealed type is "Any" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAsUpperBoundAndIndexedAssign] from typing import TypeVar, Generic, TypedDict class BaseDict(TypedDict, total=False): foo: int _DICT_T = TypeVar('_DICT_T', bound=BaseDict) class SomeGeneric(Generic[_DICT_T]): def __init__(self, data: _DICT_T) -> None: self._data: _DICT_T = data def set_state(self) -> None: self._data['foo'] = 1 [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictCreatedWithEmptyDict] from typing import TypedDict class TD(TypedDict, total=False): foo: int bar: int d: TD = dict() d2: TD = dict(foo=1) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictBytesKey] from typing import TypedDict class TD(TypedDict): foo: int d: TD = {b'foo': 2} # E: Expected TypedDict key to be string literal d[b'foo'] = 3 # E: TypedDict key must be a string literal; expected one of ("foo") \ # E: Argument 1 to "__setitem__" has incompatible type "bytes"; expected "str" d[b'foo'] # E: TypedDict key must be a string literal; expected one of ("foo") d[3] # E: TypedDict key must be a string literal; expected one of ("foo") d[True] # E: TypedDict key must be a string literal; expected one of ("foo") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUppercaseKey] from typing import TypedDict Foo = TypedDict('Foo', {'camelCaseKey': str}) value: Foo = {} # E: Missing key "camelCaseKey" for TypedDict "Foo" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictWithDeferredFieldTypeEval] from typing import Generic, TypeVar, TypedDict, NotRequired class Foo(TypedDict): y: NotRequired[int] x: Outer[Inner[ForceDeferredEval]] var: Foo reveal_type(var) # N: Revealed type is "TypedDict('__main__.Foo', {'y'?: builtins.int, 'x': __main__.Outer[__main__.Inner[__main__.ForceDeferredEval]]})" T1 = TypeVar("T1") class Outer(Generic[T1]): pass T2 = TypeVar("T2", bound="ForceDeferredEval") class Inner(Generic[T2]): pass class ForceDeferredEval: pass [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictRequiredUnimportedAny] # flags: --disallow-any-unimported from typing import NotRequired, TypedDict, ReadOnly from nonexistent import Foo # type: ignore[import-not-found] class Bar(TypedDict): foo: NotRequired[Foo] # E: Type of variable becomes "Any" due to an unfollowed import bar: ReadOnly[Foo] # E: Type of variable becomes "Any" due to an unfollowed import baz: NotRequired[ReadOnly[Foo]] # E: Type of variable becomes "Any" due to an unfollowed import [typing fixtures/typing-typeddict.pyi] -- Required[] [case testDoesRecognizeRequiredInTypedDictWithClass] from typing import TypedDict from typing import Required class Movie(TypedDict, total=False): title: Required[str] year: int m = Movie(title='The Matrix') m = Movie() # E: Missing key "title" for TypedDict "Movie" [typing fixtures/typing-typeddict.pyi] [case testDoesRecognizeRequiredInTypedDictWithAssignment] from typing import TypedDict from typing import Required Movie = TypedDict('Movie', { 'title': Required[str], 'year': int, }, total=False) m = Movie(title='The Matrix') m = Movie() # E: Missing key "title" for TypedDict "Movie" [typing fixtures/typing-typeddict.pyi] [case testDoesDisallowRequiredOutsideOfTypedDict] from typing import Required x: Required[int] = 42 # E: Required[] can be only used in a TypedDict definition [typing fixtures/typing-typeddict.pyi] [case testDoesOnlyAllowRequiredInsideTypedDictAtTopLevel] from typing import TypedDict from typing import Union from typing import Required Movie = TypedDict('Movie', { 'title': Union[ Required[str], # E: Required[] can be only used in a TypedDict definition bytes ], 'year': int, }, total=False) [typing fixtures/typing-typeddict.pyi] [case testDoesDisallowRequiredInsideRequired] from typing import TypedDict from typing import Union from typing import Required Movie = TypedDict('Movie', { 'title': Required[Union[ Required[str], # E: Required[] can be only used in a TypedDict definition bytes ]], 'year': int, }, total=False) [typing fixtures/typing-typeddict.pyi] [case testRequiredOnlyAllowsOneItem] from typing import TypedDict from typing import Required class Movie(TypedDict, total=False): title: Required[str, bytes] # E: Required[] must have exactly one type argument year: int [typing fixtures/typing-typeddict.pyi] [case testRequiredExplicitAny] # flags: --disallow-any-explicit from typing import TypedDict from typing import Required Foo = TypedDict("Foo", {"a.x": Required[int]}) [typing fixtures/typing-typeddict.pyi] -- NotRequired[] [case testDoesRecognizeNotRequiredInTypedDictWithClass] from typing import TypedDict from typing import NotRequired class Movie(TypedDict): title: str year: NotRequired[int] m = Movie(title='The Matrix') m = Movie() # E: Missing key "title" for TypedDict "Movie" [typing fixtures/typing-typeddict.pyi] [case testDoesRecognizeNotRequiredInTypedDictWithAssignment] from typing import TypedDict from typing import NotRequired Movie = TypedDict('Movie', { 'title': str, 'year': NotRequired[int], }) m = Movie(title='The Matrix') m = Movie() # E: Missing key "title" for TypedDict "Movie" [typing fixtures/typing-typeddict.pyi] [case testDoesDisallowNotRequiredOutsideOfTypedDict] from typing import NotRequired x: NotRequired[int] = 42 # E: NotRequired[] can be only used in a TypedDict definition [typing fixtures/typing-typeddict.pyi] [case testDoesOnlyAllowNotRequiredInsideTypedDictAtTopLevel] from typing import TypedDict from typing import Union from typing import NotRequired Movie = TypedDict('Movie', { 'title': Union[ NotRequired[str], # E: NotRequired[] can be only used in a TypedDict definition bytes ], 'year': int, }) [typing fixtures/typing-typeddict.pyi] [case testDoesDisallowNotRequiredInsideNotRequired] from typing import TypedDict from typing import Union from typing import NotRequired Movie = TypedDict('Movie', { 'title': NotRequired[Union[ NotRequired[str], # E: NotRequired[] can be only used in a TypedDict definition bytes ]], 'year': int, }) [typing fixtures/typing-typeddict.pyi] [case testNotRequiredOnlyAllowsOneItem] from typing import TypedDict from typing import NotRequired class Movie(TypedDict): title: NotRequired[str, bytes] # E: NotRequired[] must have exactly one type argument year: int [typing fixtures/typing-typeddict.pyi] [case testNotRequiredExplicitAny] # flags: --disallow-any-explicit from typing import TypedDict from typing import NotRequired Foo = TypedDict("Foo", {"a.x": NotRequired[int]}) [typing fixtures/typing-typeddict.pyi] -- Union dunders [case testTypedDictUnionGetItem] from typing import TypedDict, Union class Foo1(TypedDict): z: str a: int class Foo2(TypedDict): z: str b: int def func(foo: Union[Foo1, Foo2]) -> str: reveal_type(foo["z"]) # N: Revealed type is "builtins.str" # ok, but type is incorrect: reveal_type(foo.__getitem__("z")) # N: Revealed type is "builtins.object" reveal_type(foo["a"]) # N: Revealed type is "builtins.int | Any" \ # E: TypedDict "Foo2" has no key "a" reveal_type(foo["b"]) # N: Revealed type is "Any | builtins.int" \ # E: TypedDict "Foo1" has no key "b" reveal_type(foo["missing"]) # N: Revealed type is "Any" \ # E: TypedDict "Foo1" has no key "missing" \ # E: TypedDict "Foo2" has no key "missing" reveal_type(foo[1]) # N: Revealed type is "Any" \ # E: TypedDict key must be a string literal; expected one of ("z", "a") \ # E: TypedDict key must be a string literal; expected one of ("z", "b") return foo["z"] [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnionSetItem] from typing import TypedDict, Union class Foo1(TypedDict): z: str a: int class Foo2(TypedDict): z: str b: int def func(foo: Union[Foo1, Foo2]): foo["z"] = "a" # ok foo.__setitem__("z", "a") # ok foo["z"] = 1 # E: Value of "z" has incompatible type "int"; expected "str" foo["a"] = 1 # E: TypedDict "Foo2" has no key "a" foo["b"] = 2 # E: TypedDict "Foo1" has no key "b" foo["missing"] = 1 # E: TypedDict "Foo1" has no key "missing" \ # E: TypedDict "Foo2" has no key "missing" foo[1] = "m" # E: TypedDict key must be a string literal; expected one of ("z", "a") \ # E: TypedDict key must be a string literal; expected one of ("z", "b") \ # E: Argument 1 to "__setitem__" has incompatible type "int"; expected "str" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnionDelItem] from typing import TypedDict, Union class Foo1(TypedDict): z: str a: int class Foo2(TypedDict): z: str b: int def func(foo: Union[Foo1, Foo2]): del foo["z"] # E: Key "z" of TypedDict "Foo1" cannot be deleted \ # E: Key "z" of TypedDict "Foo2" cannot be deleted foo.__delitem__("z") # E: Key "z" of TypedDict "Foo1" cannot be deleted \ # E: Key "z" of TypedDict "Foo2" cannot be deleted del foo["a"] # E: Key "a" of TypedDict "Foo1" cannot be deleted \ # E: TypedDict "Foo2" has no key "a" del foo["b"] # E: TypedDict "Foo1" has no key "b" \ # E: Key "b" of TypedDict "Foo2" cannot be deleted del foo["missing"] # E: TypedDict "Foo1" has no key "missing" \ # E: TypedDict "Foo2" has no key "missing" del foo[1] # E: Argument 1 to "__delitem__" has incompatible type "int"; expected "str" \ # E: Expected TypedDict key to be string literal [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictTypeVarUnionSetItem] from typing import TypedDict, Union, TypeVar F1 = TypeVar('F1', bound='Foo1') F2 = TypeVar('F2', bound='Foo2') class Foo1(TypedDict): z: str a: int class Foo2(TypedDict): z: str b: int def func(foo: Union[F1, F2]): foo["z"] = "a" # ok foo["z"] = 1 # E: Value of "z" has incompatible type "int"; expected "str" foo["a"] = 1 # E: TypedDict "Foo2" has no key "a" foo["b"] = 2 # E: TypedDict "Foo1" has no key "b" foo["missing"] = 1 # E: TypedDict "Foo1" has no key "missing" \ # E: TypedDict "Foo2" has no key "missing" foo[1] = "m" # E: TypedDict key must be a string literal; expected one of ("z", "a") \ # E: TypedDict key must be a string literal; expected one of ("z", "b") \ # E: Argument 1 to "__setitem__" has incompatible type "int"; expected "str" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testGenericTypedDictCreation] from typing import TypedDict, Generic, TypeVar T = TypeVar("T") class TD(TypedDict, Generic[T]): key: int value: T tds: TD[str] reveal_type(tds) # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.str})" tdi = TD(key=0, value=0) reveal_type(tdi) # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.int})" TD[str](key=0, value=0) # E: Incompatible types (expression has type "int", TypedDict item "value" has type "str") TD[str]({"key": 0, "value": 0}) # E: Incompatible types (expression has type "int", TypedDict item "value" has type "str") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testGenericTypedDictInference] from typing import TypedDict, Generic, TypeVar, List T = TypeVar("T") class TD(TypedDict, Generic[T]): key: int value: T def foo(x: TD[T]) -> List[T]: ... reveal_type(foo(TD(key=1, value=2))) # N: Revealed type is "builtins.list[builtins.int]" reveal_type(foo({"key": 1, "value": 2})) # N: Revealed type is "builtins.list[builtins.int]" reveal_type(foo(dict(key=1, value=2))) # N: Revealed type is "builtins.list[builtins.int]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testGenericTypedDictExtending] from typing import TypedDict, Generic, TypeVar, List T = TypeVar("T") class TD(TypedDict, Generic[T]): key: int value: T S = TypeVar("S") class STD(TD[List[S]]): other: S std: STD[str] reveal_type(std) # N: Revealed type is "TypedDict('__main__.STD', {'key': builtins.int, 'value': builtins.list[builtins.str], 'other': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testGenericTypedDictExtendingErrors] from typing import TypedDict, Generic, TypeVar T = TypeVar("T") class Base(TypedDict, Generic[T]): x: T class Sub(Base[{}]): # E: Invalid TypedDict type argument \ # E: Type expected within [...] \ # E: Invalid base class "Base" y: int s: Sub reveal_type(s) # N: Revealed type is "TypedDict('__main__.Sub', {'y': builtins.int})" class Sub2(Base[int, str]): # E: Invalid number of type arguments for "Base" \ # E: "Base" expects 1 type argument, but 2 given y: int s2: Sub2 reveal_type(s2) # N: Revealed type is "TypedDict('__main__.Sub2', {'x': Any, 'y': builtins.int})" class Sub3(Base): # OK y: int s3: Sub3 reveal_type(s3) # N: Revealed type is "TypedDict('__main__.Sub3', {'x': Any, 'y': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testGenericTypedDictUpdate] from typing import TypedDict, Generic, TypeVar T = TypeVar("T") class Group(TypedDict, Generic[T]): a: T value: Group[int] = {"a": 1} def func(value2: Group[int]) -> None: value.update(value2) value.update({"a": 2}) value.update({"a": "string"}) # E: Incompatible types (expression has type "str", TypedDict item "a" has type "int") S = TypeVar("S") class MultiField(TypedDict, Generic[T, S]): x: T y: S mf1: MultiField[int, str] = {"x": 1, "y": "a"} mf2: MultiField[int, str] = {"x": 2, "y": "b"} mf1.update(mf2) mf3: MultiField[str, str] = {"x": "test", "y": "c"} mf1.update(mf3) # E: Argument 1 to "update" of "TypedDict" has incompatible type "MultiField[str, str]"; expected "TypedDict({'x': int, 'y': str})" mf1.update({"x": 3}) mf1.update({"y": "d"}) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAttributeOnClassObject] from typing import TypedDict class TD(TypedDict): x: str y: str reveal_type(TD.__iter__) # N: Revealed type is "def (typing._TypedDict) -> typing.Iterator[builtins.str]" reveal_type(TD.__annotations__) # N: Revealed type is "typing.Mapping[builtins.str, builtins.object]" reveal_type(TD.values) # N: Revealed type is "def (self: typing.Mapping[builtins.str, builtins.object]) -> typing.Iterable[builtins.object]" [builtins fixtures/dict-full.pyi] [typing fixtures/typing-typeddict.pyi] [case testGenericTypedDictAlias] # flags: --disallow-any-generics from typing import TypedDict, Generic, TypeVar, List T = TypeVar("T") class TD(TypedDict, Generic[T]): key: int value: T Alias = TD[List[T]] ad: Alias[str] reveal_type(ad) # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.list[builtins.str]})" Alias[str](key=0, value=0) # E: Incompatible types (expression has type "int", TypedDict item "value" has type "list[str]") # Generic aliases are *always* filled with Any, so this is different from TD(...) call. Alias(key=0, value=0) # E: Missing type arguments for generic type "Alias" \ # E: Incompatible types (expression has type "int", TypedDict item "value" has type "list[Any]") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testGenericTypedDictMultipleGenerics] # See https://github.com/python/mypy/issues/13755 from typing import Generic, TypeVar, TypedDict T = TypeVar("T") Foo = TypedDict("Foo", {"bar": T}) class Stack(Generic[T]): pass a = Foo[str] b = Foo[int] reveal_type(a) # N: Revealed type is "def (*, bar: builtins.str) -> TypedDict('__main__.Foo', {'bar': builtins.str})" reveal_type(b) # N: Revealed type is "def (*, bar: builtins.int) -> TypedDict('__main__.Foo', {'bar': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testGenericTypedDictCallSyntax] from typing import TypedDict, TypeVar T = TypeVar("T") TD = TypedDict("TD", {"key": int, "value": T}) reveal_type(TD) # N: Revealed type is "def [T] (*, key: builtins.int, value: T`1) -> TypedDict('__main__.TD', {'key': builtins.int, 'value': T`1})" tds: TD[str] reveal_type(tds) # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.str})" tdi = TD(key=0, value=0) reveal_type(tdi) # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.int})" TD[str](key=0, value=0) # E: Incompatible types (expression has type "int", TypedDict item "value" has type "str") TD[str]({"key": 0, "value": 0}) # E: Incompatible types (expression has type "int", TypedDict item "value" has type "str") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictSelfItemNotAllowed] from typing import Self, TypedDict, Optional class TD(TypedDict): val: int next: Optional[Self] # E: Self type cannot be used in TypedDict item type TDC = TypedDict("TDC", {"val": int, "next": Optional[Self]}) # E: Self type cannot be used in TypedDict item type [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testUnionOfEquivalentTypedDictsInferred] from typing import TypedDict, Dict D = TypedDict("D", {"foo": int}, total=False) def f(d: Dict[str, D]) -> None: args = d["a"] args.update(d.get("b", {})) # OK [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testUnionOfEquivalentTypedDictsDeclared] from typing import TypedDict, Union class A(TypedDict, total=False): name: str class B(TypedDict, total=False): name: str def foo(data: Union[A, B]) -> None: ... foo({"name": "Robert"}) # OK [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testUnionOfEquivalentTypedDictsEmpty] from typing import TypedDict, Union class Foo(TypedDict, total=False): foo: str class Bar(TypedDict, total=False): bar: str def foo(body: Union[Foo, Bar] = {}) -> None: # OK ... [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testUnionOfEquivalentTypedDictsDistinct] from typing import TypedDict, Union, Literal class A(TypedDict): type: Literal['a'] value: bool class B(TypedDict): type: Literal['b'] value: str Response = Union[A, B] def method(message: Response) -> None: ... method({'type': 'a', 'value': True}) # OK method({'type': 'b', 'value': 'abc'}) # OK method({'type': 'a', 'value': 'abc'}) # E: Type of TypedDict is ambiguous, none of ("A", "B") matches cleanly \ # E: Argument 1 to "method" has incompatible type "dict[str, str]"; expected "A | B" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testUnionOfEquivalentTypedDictsNested] from typing import TypedDict, Union class A(TypedDict, total=False): foo: C class B(TypedDict, total=False): foo: D class C(TypedDict, total=False): c: str class D(TypedDict, total=False): d: str def foo(data: Union[A, B]) -> None: ... foo({"foo": {"c": "foo"}}) # OK foo({"foo": {"e": "foo"}}) # E: Type of TypedDict is ambiguous, none of ("A", "B") matches cleanly \ # E: Argument 1 to "foo" has incompatible type "dict[str, dict[str, str]]"; expected "A | B" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictMissingEmptyKey] from typing import TypedDict class A(TypedDict): my_attr_1: str my_attr_2: int d: A d[''] # E: TypedDict "A" has no key "" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictFlexibleUpdate] from typing import TypedDict A = TypedDict("A", {"foo": int, "bar": int}) B = TypedDict("B", {"foo": int}) a = A({"foo": 1, "bar": 2}) b = B({"foo": 2}) a.update({"foo": 2}) a.update(b) a.update(a) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictStrictUpdate] # flags: --extra-checks from typing import TypedDict A = TypedDict("A", {"foo": int, "bar": int}) B = TypedDict("B", {"foo": int}) a = A({"foo": 1, "bar": 2}) b = B({"foo": 2}) a.update({"foo": 2}) # OK a.update(b) # E: Argument 1 to "update" of "TypedDict" has incompatible type "B"; expected "TypedDict({'foo': int, 'bar'?: int})" a.update(a) # OK [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictFlexibleUpdateUnion] from typing import TypedDict, Union A = TypedDict("A", {"foo": int, "bar": int}) B = TypedDict("B", {"foo": int}) C = TypedDict("C", {"bar": int}) a = A({"foo": 1, "bar": 2}) u: Union[B, C] a.update(u) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictFlexibleUpdateUnionExtra] from typing import TypedDict, Union A = TypedDict("A", {"foo": int, "bar": int}) B = TypedDict("B", {"foo": int, "extra": int}) C = TypedDict("C", {"bar": int, "extra": int}) a = A({"foo": 1, "bar": 2}) u: Union[B, C] a.update(u) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictFlexibleUpdateUnionStrict] # flags: --extra-checks from typing import TypedDict, Union, NotRequired A = TypedDict("A", {"foo": int, "bar": int}) A1 = TypedDict("A1", {"foo": int, "bar": NotRequired[int]}) A2 = TypedDict("A2", {"foo": NotRequired[int], "bar": int}) B = TypedDict("B", {"foo": int}) C = TypedDict("C", {"bar": int}) a = A({"foo": 1, "bar": 2}) u: Union[B, C] a.update(u) # E: Argument 1 to "update" of "TypedDict" has incompatible type "B | C"; expected "TypedDict({'foo': int, 'bar'?: int}) | TypedDict({'foo'?: int, 'bar': int})" u2: Union[A1, A2] a.update(u2) # OK [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackSame] # flags: --extra-checks from typing import TypedDict class Foo(TypedDict): a: int b: int foo1: Foo = {"a": 1, "b": 1} foo2: Foo = {**foo1, "b": 2} foo3 = Foo(**foo1, b=2) foo4 = Foo({**foo1, "b": 2}) foo5 = Foo(dict(**foo1, b=2)) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackCompatible] # flags: --extra-checks from typing import TypedDict class Foo(TypedDict): a: int class Bar(TypedDict): a: int b: int foo: Foo = {"a": 1} bar: Bar = {**foo, "b": 2} [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackIncompatible] from typing import TypedDict class Foo(TypedDict): a: int b: str class Bar(TypedDict): a: int b: int foo: Foo = {"a": 1, "b": "a"} bar1: Bar = {**foo, "b": 2} # Incompatible item is overridden bar2: Bar = {**foo, "a": 2} # E: Incompatible types (expression has type "str", TypedDict item "b" has type "int") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackNotRequiredKeyIncompatible] from typing import TypedDict, NotRequired class Foo(TypedDict): a: NotRequired[str] class Bar(TypedDict): a: NotRequired[int] foo: Foo = {} bar: Bar = {**foo} # E: Incompatible types (expression has type "str", TypedDict item "a" has type "int") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackMissingOrExtraKey] from typing import TypedDict class Foo(TypedDict): a: int class Bar(TypedDict): a: int b: int foo1: Foo = {"a": 1} bar1: Bar = {"a": 1, "b": 1} foo2: Foo = {**bar1} # E: Extra key "b" for TypedDict "Foo" bar2: Bar = {**foo1} # E: Missing key "b" for TypedDict "Bar" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackNotRequiredKeyExtra] from typing import TypedDict, NotRequired class Foo(TypedDict): a: int class Bar(TypedDict): a: int b: NotRequired[int] foo1: Foo = {"a": 1} bar1: Bar = {"a": 1} foo2: Foo = {**bar1} # E: Extra key "b" for TypedDict "Foo" bar2: Bar = {**foo1} [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackRequiredKeyMissing] from typing import TypedDict, NotRequired class Foo(TypedDict): a: NotRequired[int] class Bar(TypedDict): a: int foo: Foo = {"a": 1} bar: Bar = {**foo} # E: Missing key "a" for TypedDict "Bar" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackMultiple] # flags: --extra-checks from typing import TypedDict class Foo(TypedDict): a: int class Bar(TypedDict): b: int class Baz(TypedDict): a: int b: int c: int foo: Foo = {"a": 1} bar: Bar = {"b": 1} baz: Baz = {**foo, **bar, "c": 1} [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackNested] from typing import TypedDict class Foo(TypedDict): a: int b: int class Bar(TypedDict): c: Foo d: int foo: Foo = {"a": 1, "b": 1} bar: Bar = {"c": foo, "d": 1} bar2: Bar = {**bar, "c": {**bar["c"], "b": 2}, "d": 2} [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackNestedError] from typing import TypedDict class Foo(TypedDict): a: int b: int class Bar(TypedDict): c: Foo d: int foo: Foo = {"a": 1, "b": 1} bar: Bar = {"c": foo, "d": 1} bar2: Bar = {**bar, "c": {**bar["c"], "b": "wrong"}, "d": 2} # E: Incompatible types (expression has type "str", TypedDict item "b" has type "int") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackOverrideRequired] from typing import TypedDict Details = TypedDict('Details', {'first_name': str, 'last_name': str}) DetailsSubset = TypedDict('DetailsSubset', {'first_name': str, 'last_name': str}, total=False) defaults: Details = {'first_name': 'John', 'last_name': 'Luther'} def generate(data: DetailsSubset) -> Details: return {**defaults, **data} # OK [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackUntypedDict] from typing import Any, Dict, TypedDict class Bar(TypedDict): pass foo: Dict[str, Any] = {} bar: Bar = {**foo} # E: Unsupported type "dict[str, Any]" for ** expansion in TypedDict [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackIntoUnion] from typing import TypedDict, Union class Foo(TypedDict): a: int class Bar(TypedDict): b: int foo: Foo = {'a': 1} foo_or_bar: Union[Foo, Bar] = {**foo} [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackFromUnion] from typing import TypedDict, Union class Foo(TypedDict): a: int b: int class Bar(TypedDict): b: int foo_or_bar: Union[Foo, Bar] = {'b': 1} foo: Bar = {**foo_or_bar} # E: Extra key "a" for TypedDict "Bar" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackUnionRequiredMissing] from typing import TypedDict, NotRequired, Union class Foo(TypedDict): a: int b: int class Bar(TypedDict): a: int b: NotRequired[int] foo_or_bar: Union[Foo, Bar] = {"a": 1} foo: Foo = {**foo_or_bar} # E: Missing key "b" for TypedDict "Foo" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackInference] from typing import TypedDict, Generic, TypeVar class Foo(TypedDict): a: int b: str T = TypeVar("T") class TD(TypedDict, Generic[T]): a: T b: str foo: Foo bar = TD(**foo) reveal_type(bar) # N: Revealed type is "TypedDict('__main__.TD', {'a': builtins.int, 'b': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackStrictMode] # flags: --extra-checks from typing import TypedDict, NotRequired class Foo(TypedDict): a: int class Bar(TypedDict): a: int b: NotRequired[int] foo: Foo bar: Bar = {**foo} # E: Non-required key "b" not explicitly found in any ** item [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackAny] from typing import Any, TypedDict, NotRequired, Dict, Union class Foo(TypedDict): a: int b: NotRequired[int] x: Any y: Dict[Any, Any] z: Union[Any, Dict[Any, Any]] t1: Foo = {**x} # E: Missing key "a" for TypedDict "Foo" t2: Foo = {**y} # E: Missing key "a" for TypedDict "Foo" t3: Foo = {**z} # E: Missing key "a" for TypedDict "Foo" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackError] from typing import TypedDict class Foo(TypedDict): a: int def foo(x: int) -> Foo: ... f: Foo = {**foo("no")} # E: Argument 1 to "foo" has incompatible type "str"; expected "int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictWith__or__method] from typing import Dict, TypedDict class Foo(TypedDict): key: int foo1: Foo = {'key': 1} foo2: Foo = {'key': 2} reveal_type(foo1 | foo2) # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})" reveal_type(foo1 | {'key': 1}) # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})" reveal_type(foo1 | {'key': 'a'}) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]" reveal_type(foo1 | {}) # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})" d1: Dict[str, int] d2: Dict[int, str] reveal_type(foo1 | d1) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]" foo1 | d2 # E: Unsupported operand types for | ("Foo" and "dict[int, str]") class Bar(TypedDict): key: int value: str bar: Bar reveal_type(bar | {}) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})" reveal_type(bar | {'key': 1, 'value': 'v'}) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})" reveal_type(bar | {'key': 1}) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})" reveal_type(bar | {'value': 'v'}) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})" reveal_type(bar | {'key': 'a'}) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]" reveal_type(bar | {'value': 1}) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]" reveal_type(bar | {'key': 'a', 'value': 1}) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]" reveal_type(bar | foo1) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})" reveal_type(bar | d1) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]" bar | d2 # E: Unsupported operand types for | ("Bar" and "dict[int, str]") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict-iror.pyi] [case testTypedDictWith__or__method_error] from typing import TypedDict class Foo(TypedDict): key: int foo: Foo = {'key': 1} foo | 1 class SubDict(dict): ... reveal_type(foo | SubDict()) [out] main:7: error: No overload variant of "__or__" of "TypedDict" matches argument type "int" main:7: note: Possible overload variants: main:7: note: def __or__(self, TypedDict({'key'?: int}), /) -> Foo main:7: note: def __or__(self, dict[str, Any], /) -> dict[str, object] main:10: note: Revealed type is "builtins.dict[builtins.str, builtins.object]" [builtins fixtures/dict-full.pyi] [typing fixtures/typing-typeddict-iror.pyi] [case testTypedDictWith__ror__method] from typing import Dict, TypedDict class Foo(TypedDict): key: int foo: Foo = {'key': 1} reveal_type({'key': 1} | foo) # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})" reveal_type({'key': 'a'} | foo) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]" reveal_type({} | foo) # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})" {1: 'a'} | foo # E: Dict entry 0 has incompatible type "int": "str"; expected "str": "Any" d1: Dict[str, int] d2: Dict[int, str] reveal_type(d1 | foo) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]" d2 | foo # E: Unsupported operand types for | ("dict[int, str]" and "Foo") 1 | foo # E: No overload variant of "__ror__" of "TypedDict" matches argument type "int" \ # N: Possible overload variants: \ # N: def __ror__(self, TypedDict({'key'?: int}), /) -> Foo \ # N: def __ror__(self, dict[str, Any], /) -> dict[str, object] class Bar(TypedDict): key: int value: str bar: Bar reveal_type({} | bar) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})" reveal_type({'key': 1, 'value': 'v'} | bar) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})" reveal_type({'key': 1} | bar) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})" reveal_type({'value': 'v'} | bar) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})" reveal_type({'key': 'a'} | bar) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]" reveal_type({'value': 1} | bar) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]" reveal_type({'key': 'a', 'value': 1} | bar) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]" reveal_type(d1 | bar) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]" d2 | bar # E: Unsupported operand types for | ("dict[int, str]" and "Bar") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict-iror.pyi] [case testTypedDictWith__ior__method] from typing import Dict, TypedDict class Foo(TypedDict): key: int foo: Foo = {'key': 1} foo |= {'key': 2} foo |= {} foo |= {'key': 'a', 'b': 'a'} # E: Expected TypedDict key "key" but found keys ("key", "b") \ # E: Incompatible types (expression has type "str", TypedDict item "key" has type "int") foo |= {'b': 2} # E: Unexpected TypedDict key "b" d1: Dict[str, int] d2: Dict[int, str] foo |= d1 # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "dict[str, int]"; expected "TypedDict({'key'?: int})" foo |= d2 # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "dict[int, str]"; expected "TypedDict({'key'?: int})" class Bar(TypedDict): key: int value: str bar: Bar bar |= {} bar |= {'key': 1, 'value': 'a'} bar |= {'key': 'a', 'value': 'a', 'b': 'a'} # E: Expected TypedDict keys ("key", "value") but found keys ("key", "value", "b") \ # E: Incompatible types (expression has type "str", TypedDict item "key" has type "int") bar |= foo bar |= d1 # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "dict[str, int]"; expected "TypedDict({'key'?: int, 'value'?: str})" bar |= d2 # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "dict[int, str]"; expected "TypedDict({'key'?: int, 'value'?: str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict-iror.pyi] [case testGenericTypedDictStrictOptionalExtending] from typing import Generic, TypeVar, TypedDict, Optional T = TypeVar("T") class Foo(TypedDict, Generic[T], total=False): a: Optional[str] g: Optional[T] class Bar(Foo[T], total=False): other: str b: Bar[int] reveal_type(b["a"]) # N: Revealed type is "builtins.str | None" reveal_type(b["g"]) # N: Revealed type is "builtins.int | None" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testNoCrashOnUnImportedAnyNotRequired] # flags: --disallow-any-unimported from typing import NotRequired, Required, TypedDict from thismoduledoesntexist import T # type: ignore[import] B = TypedDict("B", { # E: Type of a TypedDict key becomes "Any" due to an unfollowed import "T1": NotRequired[T], "T2": Required[T], }) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictWithClassLevelKeywords_no_native_parse] from typing import TypedDict, Generic, TypeVar T = TypeVar('T') class Meta(type): ... class WithMetaKeyword(TypedDict, metaclass=Meta): # E: Unexpected keyword argument "metaclass" for "__init_subclass__" of "TypedDict" ... class GenericWithMetaKeyword(TypedDict, Generic[T], metaclass=Meta): # E: Unexpected keyword argument "metaclass" for "__init_subclass__" of "TypedDict" ... # We still don't allow this, because the implementation is much easier # and it does not make any practical sense to do it: class WithTypeMeta(TypedDict, metaclass=type): # E: Unexpected keyword argument "metaclass" for "__init_subclass__" of "TypedDict" ... class OtherKeywords(TypedDict, a=1, b=2, c=3, total=True): # E: Unexpected keyword argument "a" for "__init_subclass__" of "TypedDict" \ # E: Unexpected keyword argument "b" for "__init_subclass__" of "TypedDict" \ # E: Unexpected keyword argument "c" for "__init_subclass__" of "TypedDict" ... class TotalInTheMiddle(TypedDict, a=1, total=True, b=2, c=3): # E: Unexpected keyword argument "a" for "__init_subclass__" of "TypedDict" \ # E: Unexpected keyword argument "b" for "__init_subclass__" of "TypedDict" \ # E: Unexpected keyword argument "c" for "__init_subclass__" of "TypedDict" ... [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanCreateClassWithFunctionBasedTypedDictBase] from typing import TypedDict class Params(TypedDict("Params", {'x': int})): pass p: Params = {'x': 2} reveal_type(p) # N: Revealed type is "TypedDict('__main__.Params', {'x': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testInitTypedDictFromType] from typing import TypedDict, Type from typing_extensions import Required class Point(TypedDict, total=False): x: Required[int] y: int def func(cls: Type[Point]) -> None: reveal_type(cls) # N: Revealed type is "type[TypedDict('__main__.Point', {'x': builtins.int, 'y'?: builtins.int})]" cls(x=1, y=2) cls(1, 2) # E: Too many positional arguments cls(x=1) cls(y=2) # E: Missing named argument "x" cls(x=1, y=2, error="") # E: Unexpected keyword argument "error" [typing fixtures/typing-full.pyi] [builtins fixtures/tuple.pyi] [case testInitTypedDictFromTypeGeneric] from typing import Generic, TypedDict, Type, TypeVar from typing_extensions import Required class Point(TypedDict, total=False): x: Required[int] y: int T = TypeVar("T", bound=Point) class A(Generic[T]): def __init__(self, a: Type[T]) -> None: self.a = a def func(self) -> T: reveal_type(self.a) # N: Revealed type is "type[T`1]" self.a(x=1, y=2) self.a(y=2) # E: Missing named argument "x" return self.a(x=1) [typing fixtures/typing-full.pyi] [builtins fixtures/tuple.pyi] [case testNameUndefinedErrorDoesNotLoseUnpackedKWArgsInformation] from typing import TypedDict, overload from typing_extensions import Unpack class TD(TypedDict, total=False): x: int y: str @overload def f(self, *, x: int) -> None: ... @overload def f(self, *, y: str) -> None: ... def f(self, **kwargs: Unpack[TD]) -> None: z # E: Name "z" is not defined @overload def g(self, *, x: float) -> None: ... @overload def g(self, *, y: str) -> None: ... def g(self, **kwargs: Unpack[TD]) -> None: # E: Overloaded function implementation does not accept all possible parameters of signature 1 z # E: Name "z" is not defined class A: def f(self, *, x: int) -> None: ... def g(self, *, x: float) -> None: ... class B(A): def f(self, **kwargs: Unpack[TD]) -> None: z # E: Name "z" is not defined def g(self, **kwargs: Unpack[TD]) -> None: # E: Signature of "g" incompatible with supertype "A" \ # N: Superclass: \ # N: def g(self, *, x: float) -> None \ # N: Subclass: \ # N: def g(*, x: int = ..., y: str = ...) -> None z # E: Name "z" is not defined reveal_type(B.f) # N: Revealed type is "def (self: __main__.B, **kwargs: Unpack[TypedDict('__main__.TD', {'x'?: builtins.int, 'y'?: builtins.str})])" B().f(x=1.0) # E: Argument "x" to "f" of "B" has incompatible type "float"; expected "int" [builtins fixtures/primitives.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackWithParamSpecInference] from typing import TypedDict, TypeVar, ParamSpec, Callable from typing_extensions import Unpack P = ParamSpec("P") R = TypeVar("R") def run(func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: ... class Params(TypedDict): temperature: float def test(temperature: int) -> None: ... def test2(temperature: float, other: str) -> None: ... class Test: def f(self, c: Callable[..., None], **params: Unpack[Params]) -> None: run(c, **params) def g(self, **params: Unpack[Params]) -> None: run(test, **params) # E: Argument "temperature" to "run" has incompatible type "float"; expected "int" def h(self, **params: Unpack[Params]) -> None: run(test2, other="yes", **params) run(test2, other=0, **params) # E: Argument "other" to "run" has incompatible type "int"; expected "str" [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testTypedDictUnpackSingleWithSubtypingNoCrash] from typing import Callable, TypedDict from typing_extensions import Unpack class Kwargs(TypedDict): name: str def f(**kwargs: Unpack[Kwargs]) -> None: pass class C: d: Callable[[Unpack[Kwargs]], None] # TODO: it is an old question whether we should allow this, for now simply don't crash. class D(C): d = f [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictInlineNoOldStyleAlias] # flags: --enable-incomplete-feature=InlineTypedDict X = {"int": int, "str": str} reveal_type(X) # N: Revealed type is "builtins.dict[builtins.str, def () -> builtins.object]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictInlineYesMidStyleAlias] # flags: --enable-incomplete-feature=InlineTypedDict from typing_extensions import TypeAlias X: TypeAlias = {"int": int, "str": str} x: X reveal_type(x) # N: # N: Revealed type is "TypedDict({'int': builtins.int, 'str': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictInlineNoEmpty] # flags: --enable-incomplete-feature=InlineTypedDict x: {} # E: Invalid type comment or annotation reveal_type(x) # N: Revealed type is "Any" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictInlineNotRequired] # flags: --enable-incomplete-feature=InlineTypedDict from typing import NotRequired x: {"one": int, "other": NotRequired[int]} x = {"one": 1} # OK y: {"one": int, "other": int} y = {"one": 1} # E: Expected TypedDict keys ("one", "other") but found only key "one" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictInlineReadOnly] # flags: --enable-incomplete-feature=InlineTypedDict from typing import ReadOnly x: {"one": int, "other": ReadOnly[int]} x["one"] = 1 # ok x["other"] = 1 # E: ReadOnly TypedDict key "other" TypedDict is mutated [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictInlineNestedSchema] # flags: --enable-incomplete-feature=InlineTypedDict def nested() -> {"one": str, "other": {"a": int, "b": int}}: if bool(): return {"one": "yes", "other": {"a": 1, "b": 2}} # OK else: return {"one": "no", "other": {"a": 1, "b": "2"}} # E: Incompatible types (expression has type "str", TypedDict item "b" has type "int") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictInlineMergeAnother] # flags: --enable-incomplete-feature=InlineTypedDict from typing import TypeVar from typing_extensions import TypeAlias T = TypeVar("T") X: TypeAlias = {"item": T} x: {"a": int, **X[str], "b": int} reveal_type(x) # N: Revealed type is "TypedDict({'a': builtins.int, 'b': builtins.int, 'item': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] # ReadOnly # See: https://peps.python.org/pep-0705 [case testTypedDictReadOnly] # flags: --show-error-codes from typing import ReadOnly, TypedDict class TP(TypedDict): one: int other: ReadOnly[str] x: TP reveal_type(x["one"]) # N: Revealed type is "builtins.int" reveal_type(x["other"]) # N: Revealed type is "builtins.str" x["one"] = 1 # ok x["other"] = "a" # E: ReadOnly TypedDict key "other" TypedDict is mutated [typeddict-readonly-mutated] [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictFunctionalSyntaxWithMultipleSpecialForms] from typing import ReadOnly, Required, NotRequired, TypedDict from typing_extensions import Annotated D1 = TypedDict("D1", {"x": int, "y": ReadOnly[Required[int]]}, total=False) D2 = TypedDict("D2", {"x": int, "y": Required[ReadOnly[int]]}, total=False) D3 = TypedDict("D3", {"x": int, "y": ReadOnly[NotRequired[int]]}) D4 = TypedDict("D4", {"x": int, "y": NotRequired[ReadOnly[int]]}) D5 = TypedDict("D5", {"x": int, "y": Annotated[ReadOnly[int], "some annotation text"]}) D6 = TypedDict("D6", {"x": int, "y": ReadOnly[Annotated[int, "some annotation text"]]}) D7 = TypedDict("D7", {"x": int, "y": Annotated[ReadOnly[NotRequired[int]], "some annotation text"]}) D8 = TypedDict("D8", {"x": int, "y": NotRequired[ReadOnly[Annotated[int, "some annotation text"]]]}) d1: D1 d2: D2 d3: D3 d4: D4 d5: D5 d6: D6 d7: D7 d8: D8 reveal_type(d1) # N: Revealed type is "TypedDict('__main__.D1', {'x'?: builtins.int, 'y'=: builtins.int})" reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'x'?: builtins.int, 'y'=: builtins.int})" reveal_type(d3) # N: Revealed type is "TypedDict('__main__.D3', {'x': builtins.int, 'y'?=: builtins.int})" reveal_type(d4) # N: Revealed type is "TypedDict('__main__.D4', {'x': builtins.int, 'y'?=: builtins.int})" reveal_type(d5) # N: Revealed type is "TypedDict('__main__.D5', {'x': builtins.int, 'y'=: builtins.int})" reveal_type(d6) # N: Revealed type is "TypedDict('__main__.D6', {'x': builtins.int, 'y'=: builtins.int})" reveal_type(d7) # N: Revealed type is "TypedDict('__main__.D7', {'x': builtins.int, 'y'?=: builtins.int})" reveal_type(d8) # N: Revealed type is "TypedDict('__main__.D8', {'x': builtins.int, 'y'?=: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictFunctionalSyntaxWithContradictorySpecialForms] from typing import Required, NotRequired, TypedDict D1 = TypedDict("D1", {"x": NotRequired[Required[int]]}) # E: "Required[]" type cannot be nested D2 = TypedDict("D2", {"x": Required[NotRequired[int]]}) # E: "NotRequired[]" type cannot be nested [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyCreation] from typing import ReadOnly, TypedDict class TD(TypedDict): x: ReadOnly[int] y: int # Ok: x = TD({"x": 1, "y": 2}) y = TD(x=1, y=2) z: TD = {"x": 1, "y": 2} # Error: x2 = TD({"x": "a", "y": 2}) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") y2 = TD(x="a", y=2) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") z2: TD = {"x": "a", "y": 2} # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyDel] from typing import ReadOnly, TypedDict, NotRequired class TP(TypedDict): required_key: ReadOnly[str] optional_key: ReadOnly[NotRequired[str]] x: TP del x["required_key"] # E: Key "required_key" of TypedDict "TP" cannot be deleted del x["optional_key"] # E: Key "optional_key" of TypedDict "TP" cannot be deleted [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyMutateMethods] from typing import ReadOnly, NotRequired, TypedDict class TP(TypedDict): key: ReadOnly[str] optional_key: ReadOnly[NotRequired[str]] other: ReadOnly[int] mutable: bool x: TP reveal_type(x.pop("key")) # N: Revealed type is "builtins.str" \ # E: Key "key" of TypedDict "TP" cannot be deleted reveal_type(x.pop("optional_key")) # N: Revealed type is "builtins.str" \ # E: Key "optional_key" of TypedDict "TP" cannot be deleted x.update({"key": "abc", "other": 1, "mutable": True}) # E: ReadOnly TypedDict keys ("key", "other") TypedDict are mutated x.setdefault("key", "abc") # E: ReadOnly TypedDict key "key" TypedDict is mutated x.setdefault("optional_key", "foo") # E: ReadOnly TypedDict key "optional_key" TypedDict is mutated x.setdefault("other", 1) # E: ReadOnly TypedDict key "other" TypedDict is mutated x.setdefault("mutable", False) # ok [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictFromTypingExtensionsReadOnlyMutateMethods] from typing_extensions import ReadOnly, TypedDict class TP(TypedDict): key: ReadOnly[str] x: TP x.update({"key": "abc"}) # E: ReadOnly TypedDict key "key" TypedDict is mutated [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictFromMypyExtensionsReadOnlyMutateMethods] from mypy_extensions import TypedDict from typing_extensions import ReadOnly class TP(TypedDict): key: ReadOnly[str] x: TP x.update({"key": "abc"}) # E: ReadOnly TypedDict key "key" TypedDict is mutated [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyMutate__ior__Statements] from typing import TypedDict from typing_extensions import ReadOnly class TP(TypedDict): key: ReadOnly[str] other: ReadOnly[int] mutable: bool x: TP x |= {"mutable": True} # ok x |= {"key": "a"} # E: ReadOnly TypedDict key "key" TypedDict is mutated x |= {"key": "a", "other": 1, "mutable": True} # E: ReadOnly TypedDict keys ("key", "other") TypedDict are mutated [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict-iror.pyi] [case testTypedDictReadOnlyMutate__or__Statements] from typing import TypedDict from typing_extensions import ReadOnly class TP(TypedDict): key: ReadOnly[str] other: ReadOnly[int] mutable: bool x: TP # These are new objects, not mutation: x = x | {"mutable": True} x = x | {"key": "a"} x = x | {"key": "a", "other": 1, "mutable": True} y1 = x | {"mutable": True} y2 = x | {"key": "a"} [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict-iror.pyi] [case testTypedDictReadOnlyMutateWithOtherDicts] from typing import ReadOnly, TypedDict, Dict class TP(TypedDict): key: ReadOnly[str] mutable: bool class Mutable(TypedDict): mutable: bool class Regular(TypedDict): key: str m: Mutable r: Regular d: Dict[str, object] # Creating new objects is ok: tp: TP = {**r, **m} tp1: TP = {**tp, **m} tp2: TP = {**r, **m} tp3: TP = {**tp, **r} tp4: TP = {**tp, **d} # E: Unsupported type "dict[str, object]" for ** expansion in TypedDict [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictGenericReadOnly] from typing import ReadOnly, TypedDict, TypeVar, Generic T = TypeVar('T') class TP(TypedDict, Generic[T]): key: ReadOnly[T] x: TP[int] reveal_type(x["key"]) # N: Revealed type is "builtins.int" x["key"] = 1 # E: ReadOnly TypedDict key "key" TypedDict is mutated x["key"] = "a" # E: ReadOnly TypedDict key "key" TypedDict is mutated \ # E: Value of "key" has incompatible type "str"; expected "int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyOtherTypedDict] from typing import ReadOnly, TypedDict class First(TypedDict): field: int class TP(TypedDict): key: ReadOnly[First] x: TP reveal_type(x["key"]["field"]) # N: Revealed type is "builtins.int" x["key"]["field"] = 1 # ok x["key"] = {"field": 2} # E: ReadOnly TypedDict key "key" TypedDict is mutated [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyInheritance] from typing import ReadOnly, TypedDict class Base(TypedDict): a: ReadOnly[str] class Child(Base): b: ReadOnly[int] base: Base reveal_type(base["a"]) # N: Revealed type is "builtins.str" base["a"] = "x" # E: ReadOnly TypedDict key "a" TypedDict is mutated base["b"] # E: TypedDict "Base" has no key "b" child: Child reveal_type(child["a"]) # N: Revealed type is "builtins.str" reveal_type(child["b"]) # N: Revealed type is "builtins.int" child["a"] = "x" # E: ReadOnly TypedDict key "a" TypedDict is mutated child["b"] = 1 # E: ReadOnly TypedDict key "b" TypedDict is mutated [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlySubtyping] from typing import ReadOnly, TypedDict class A(TypedDict): key: ReadOnly[str] class B(TypedDict): key: str a: A b: B def accepts_A(d: A): ... def accepts_B(d: B): ... accepts_A(a) accepts_A(b) accepts_B(a) # E: Argument 1 to "accepts_B" has incompatible type "A"; expected "B" accepts_B(b) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyTypeVarBoundSubtyping] from typing import ReadOnly, TypedDict, TypeVar A = TypedDict('A', {'x': ReadOnly[int]}) B = TypedDict('B', {'x': int}) TA = TypeVar('TA', bound=A) TB = TypeVar('TB', bound=B) def fA(t: TA) -> TA: return t def fB(t: TB) -> TB: return t a: A b: B fA(a) fA(b) fB(a) # E: Value of type variable "TB" of "fB" cannot be "A" fB(b) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlySubclassing] from typing import ReadOnly, TypedDict class A(TypedDict): key: ReadOnly[str] class B(A): key: str a: A b: B def accepts_A(d: A): ... def accepts_B(d: B): ... accepts_A(a) accepts_A(b) accepts_B(a) # E: Argument 1 to "accepts_B" has incompatible type "A"; expected "B" accepts_B(b) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlySubclassingFieldSubtype] from typing import ReadOnly, TypedDict class A(TypedDict): key: ReadOnly[float] class B(A): key: int class C(A): key: ReadOnly[int] a: A reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {'key'=: builtins.float})" b: B reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'key': builtins.int})" c: C reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'key'=: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlySubclassingFieldSubtypeWithForwardReferenceBases] from typing import ReadOnly, TypedDict class X("XB"): pass class Y("YB"): pass class Z("ZB"): pass class A(TypedDict): key: ReadOnly["X"] class B(A): key: "Y" # ok: Y subclasses X via YB class C(A): key: "Z" # E: Definition of field "key" incompatible with base class "A" x: A y: B x = y # ok: B is a valid subtype of A class XB: pass class YB(X): pass class ZB: pass [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyIllegalSubclassingFieldSupertype] from typing import ReadOnly, TypedDict class A(TypedDict): key: ReadOnly[int] class B(A): key: float # E: Definition of field "key" incompatible with base class "A" class C(A): key: ReadOnly[float] # E: Definition of field "key" incompatible with base class "A" a: A reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {'key'=: builtins.int})" b: B reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'key': builtins.float})" c: C reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'key'=: builtins.float})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyMixinFieldSubtype] from typing import ReadOnly, TypedDict class A(TypedDict): key: ReadOnly[float] class B(TypedDict): key: ReadOnly[int] class C(B, A): # Left-most base "wins" pass class D(A, B): # E: Incompatible definitions of field "key" in base classes "B" and "A" \ # N: This can be resolved by redeclaring the field "key" with a mutually compatible type pass class E(A, B): key: ReadOnly[int] # ok: explicit redefinition c: C reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'key'=: builtins.int})" d: D reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'key'=: builtins.float})" e: E reveal_type(e) # N: Revealed type is "TypedDict('__main__.E', {'key'=: builtins.int})" # Verify that subclasses are valid subtypes a: A b: B a = c b = c a = e b = e [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlySubclassingTotality] from typing import ReadOnly, TypedDict class A(TypedDict, total=False): key: ReadOnly[int] class B(A): key: int a: A reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {'key'?=: builtins.int})" b: B reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'key': builtins.int})" a = b # ok: B is a valid subtype of A [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyIllegalSubclassingTotality] from typing import ReadOnly, TypedDict class A(TypedDict): key: ReadOnly[int] class B(A, total=False): key: int # E: Field "key" is required in base class "A" a: A reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {'key'=: builtins.int})" b: B reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'key'?: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyMixinTotality] from typing import ReadOnly, TypedDict class A(TypedDict, total=True): key: ReadOnly[int] class B(TypedDict, total=False): key: ReadOnly[int] class C(B, A): pass class D(A, B): pass c: C reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'key'=: builtins.int})" d: D reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'key'=: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyMixinWithMutableField] from typing import ReadOnly, TypedDict class A(TypedDict): key: ReadOnly[float] class B(TypedDict): key: float class C(TypedDict): key: int class D1(A, B): pass d1: D1 reveal_type(d1) # N: Revealed type is "TypedDict('__main__.D1', {'key': builtins.float})" class D2(B, A): pass d2: D2 reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'key': builtins.float})" class D3(A, C): pass d3: D3 reveal_type(d3) # N: Revealed type is "TypedDict('__main__.D3', {'key': builtins.int})" class D4(C, A): pass d4: D4 reveal_type(d4) # N: Revealed type is "TypedDict('__main__.D4', {'key': builtins.int})" class D5(A, B, C): pass # E: Incompatible definitions of field "key" in base classes "C" and "B" d5: D5 reveal_type(d5) # N: Revealed type is "TypedDict('__main__.D5', {'key': builtins.float})" class D6(C, B, A): pass # E: Incompatible definitions of field "key" in base classes "B" and "C" d6: D6 reveal_type(d6) # N: Revealed type is "TypedDict('__main__.D6', {'key': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictRequiredConsistentWithNotRequiredReadOnly] from typing import NotRequired, ReadOnly, Required, TypedDict class A(TypedDict): x: NotRequired[ReadOnly[str]] class B(TypedDict): x: Required[str] def f(b: B): a: A = b # ok [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictNotRequiredInconsistentWithRequiredReadOnly] from typing import NotRequired, ReadOnly, Required, TypedDict class A(TypedDict): x: Required[ReadOnly[str]] class B(TypedDict): x: NotRequired[str] def f(b: B): a: A = b # E: Incompatible types in assignment (expression has type "B", variable has type "A") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyCall] from typing import ReadOnly, TypedDict TP = TypedDict("TP", {"one": int, "other": ReadOnly[str]}) x: TP reveal_type(x["one"]) # N: Revealed type is "builtins.int" reveal_type(x["other"]) # N: Revealed type is "builtins.str" x["one"] = 1 # ok x["other"] = "a" # E: ReadOnly TypedDict key "other" TypedDict is mutated [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyABCSubtypes] from typing import ReadOnly, TypedDict, Mapping, Dict, MutableMapping class TP(TypedDict): one: int other: ReadOnly[int] def accepts_mapping(m: Mapping[str, object]): ... def accepts_mutable_mapping(mm: MutableMapping[str, object]): ... def accepts_dict(d: Dict[str, object]): ... x: TP accepts_mapping(x) accepts_mutable_mapping(x) # E: Argument 1 to "accepts_mutable_mapping" has incompatible type "TP"; expected "MutableMapping[str, object]" accepts_dict(x) # E: Argument 1 to "accepts_dict" has incompatible type "TP"; expected "dict[str, object]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyAndNotRequired] from typing import ReadOnly, TypedDict, NotRequired class TP(TypedDict): one: ReadOnly[NotRequired[int]] two: NotRequired[ReadOnly[str]] x: TP reveal_type(x) # N: Revealed type is "TypedDict('__main__.TP', {'one'?=: builtins.int, 'two'?=: builtins.str})" reveal_type(x.get("one")) # N: Revealed type is "builtins.int | None" reveal_type(x.get("two")) # N: Revealed type is "builtins.str | None" x["one"] = 1 # E: ReadOnly TypedDict key "one" TypedDict is mutated x["two"] = "a" # E: ReadOnly TypedDict key "two" TypedDict is mutated [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithNonOverlappingReadOnlyKeys] from typing import TypeVar, Callable, TypedDict, ReadOnly XY = TypedDict('XY', {'x': ReadOnly[int], 'y': int}) YZ = TypedDict('YZ', {'y': int, 'z': ReadOnly[int]}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: XY, y: YZ) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'=: builtins.int, 'y': builtins.int, 'z'=: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithOverlappingReadOnlyAndMutableKeys] from typing import TypedDict, TypeVar, Callable, ReadOnly XY = TypedDict('XY', {'x': int, 'y': int}) YZ = TypedDict('YZ', {'y': ReadOnly[int], 'z': int}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: XY, y: YZ) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.int, 'z': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithDifferingMutabilityAndAny] from typing import Any, TypedDict, TypeVar, Callable, ReadOnly A = TypedDict('A', {'x': Any}) B = TypedDict('B', {'x': ReadOnly[int]}) C = TypedDict('C', {'x': ReadOnly[Any]}) D = TypedDict('D', {'x': int}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def gAB(x: A, y: B) -> None: pass def gBA(x: B, y: A) -> None: pass def gCD(x: C, y: D) -> None: pass def gDC(x: D, y: C) -> None: pass reveal_type(f(gAB)) # N: Revealed type is "TypedDict({'x': builtins.int})" reveal_type(f(gBA)) # N: Revealed type is "TypedDict({'x': builtins.int})" reveal_type(f(gCD)) # N: Revealed type is "TypedDict({'x': builtins.int})" reveal_type(f(gDC)) # N: Revealed type is "TypedDict({'x': builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithIncompatibleReadOnlyCommonKeysIsUninhabitedUnlessNotRequired] from typing import TypedDict, TypeVar, Callable, ReadOnly A = TypedDict('A', {'x': ReadOnly[int]}) B = TypedDict('B', {'x': ReadOnly[str]}) C = TypedDict('C', {'x': ReadOnly[int]}, total=False) D = TypedDict('D', {'x': ReadOnly[str]}, total=False) T = TypeVar('T') def meet(x: Callable[[T, T], None]) -> T: pass def fAB(x: A, y: B) -> None: pass def fAD(x: A, y: D) -> None: pass def fCB(x: C, y: B) -> None: pass def fCD(x: C, y: D) -> None: pass if int(): reveal_type(meet(fAB)) # N: Revealed type is "Never" if int(): reveal_type(meet(fAD)) # N: Revealed type is "Never" if int(): reveal_type(meet(fCB)) # N: Revealed type is "Never" reveal_type(meet(fCD)) # N: Revealed type is "TypedDict({'x'?=: Never})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithCompatibleReadOnlyAndMutableCommonKeys] from typing import TypedDict, TypeVar, Callable, NotRequired, ReadOnly, Union A = TypedDict('A', {'x': int, 'y': ReadOnly[Union[int, str]]}) B = TypedDict('B', {'x': ReadOnly[float], 'y': str}) C = TypedDict('C', {'x': ReadOnly[NotRequired[float]], 'y': str}) D = TypedDict('D', {'x': NotRequired[int], 'y': ReadOnly[Union[int, str]]}) T = TypeVar('T') def meet(x: Callable[[T, T], None]) -> T: pass def fAB(x: A, y: B) -> None: pass def fBA(x: B, y: A) -> None: pass def fAC(x: A, y: C) -> None: pass def fCA(x: C, y: A) -> None: pass def fCD(x: C, y: D) -> None: pass def fDC(x: D, y: C) -> None: pass reveal_type(meet(fAB)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.str})" reveal_type(meet(fBA)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.str})" reveal_type(meet(fAC)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.str})" reveal_type(meet(fCA)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.str})" reveal_type(meet(fCD)) # N: Revealed type is "TypedDict({'x'?: builtins.int, 'y': builtins.str})" reveal_type(meet(fDC)) # N: Revealed type is "TypedDict({'x'?: builtins.int, 'y': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithIncompatibleReadOnlyAndMutableCommonKeysIsUninhabited] from typing import TypedDict, TypeVar, Callable, ReadOnly XYa = TypedDict('XYa', {'x': int, 'y': ReadOnly[int]}) YbZ = TypedDict('YbZ', {'y': str, 'z': int}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: XYa, y: YbZ) -> None: pass reveal_type(f(g)) # N: Revealed type is "Never" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithCompatibleReadOnlyCommonKeys] from typing import TypedDict, TypeVar, Callable, ReadOnly A = TypedDict('A', {'a': int}) B = TypedDict('B', {'b': int}) Xa = TypedDict('Xa', {'x': ReadOnly[A]}) Xb = TypedDict('Xb', {'x': ReadOnly[B]}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: Xa, y: Xb) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'=: TypedDict({'a': builtins.int, 'b': builtins.int})})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsWithReadOnlyKeysAndAny] from typing import Any, TypedDict, TypeVar, Callable, ReadOnly A = TypedDict('A', {'x': ReadOnly[Any]}) B = TypedDict('B', {'x': ReadOnly[int]}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: A, y: B) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'=: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfReadOnlyTypedDictsWithNoCommonKeysHasAllKeysAndNewFallback] from typing import TypedDict, TypeVar, Callable, ReadOnly X = TypedDict('X', {'x': ReadOnly[int]}) Z = TypedDict('Z', {'z': ReadOnly[int]}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: X, y: Z) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'=: builtins.int, 'z'=: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfReadOnlyTypedDictsWithNonTotal] from typing import TypedDict, TypeVar, Callable, ReadOnly XY = TypedDict('XY', {'x': ReadOnly[int], 'y': ReadOnly[int]}, total=False) YZ = TypedDict('YZ', {'y': ReadOnly[int], 'z': ReadOnly[int]}, total=False) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: XY, y: YZ) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'?=: builtins.int, 'y'?=: builtins.int, 'z'?=: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfReadOnlyTypedDictsWithNonOverlappingNonTotalAndTotal] from typing import TypedDict, TypeVar, Callable, ReadOnly XY = TypedDict('XY', {'x': ReadOnly[int]}, total=False) YZ = TypedDict('YZ', {'y': ReadOnly[int], 'z': ReadOnly[int]}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: XY, y: YZ) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'?=: builtins.int, 'y'=: builtins.int, 'z'=: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfReadOnlyTypedDictsWithOverlappingNonTotalAndTotal] from typing import TypedDict, TypeVar, Callable, ReadOnly XY = TypedDict('XY', {'x': ReadOnly[int], 'y': ReadOnly[int]}, total=False) YZ = TypedDict('YZ', {'y': ReadOnly[int], 'z': ReadOnly[int]}) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: XY, y: YZ) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'?=: builtins.int, 'y'=: builtins.int, 'z'=: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyUnpack] from typing import TypedDict from typing_extensions import Unpack, ReadOnly class TD(TypedDict): x: ReadOnly[int] y: str def func(**kwargs: Unpack[TD]): kwargs["x"] = 1 # E: ReadOnly TypedDict key "x" TypedDict is mutated kwargs["y" ] = "a" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testIncorrectTypedDictSpecialFormsUsage] from typing import ReadOnly, TypedDict, NotRequired, Required x: ReadOnly[int] # E: ReadOnly[] can be only used in a TypedDict definition y: Required[int] # E: Required[] can be only used in a TypedDict definition z: NotRequired[int] # E: NotRequired[] can be only used in a TypedDict definition class TP(TypedDict): a: ReadOnly[ReadOnly[int]] # E: "ReadOnly[]" type cannot be nested b: ReadOnly[NotRequired[ReadOnly[str]]] # E: "ReadOnly[]" type cannot be nested c: NotRequired[Required[int]] # E: "Required[]" type cannot be nested d: Required[NotRequired[int]] # E: "NotRequired[]" type cannot be nested e: Required[ReadOnly[NotRequired[int]]] # E: "NotRequired[]" type cannot be nested f: ReadOnly[ReadOnly[ReadOnly[int]]] # E: "ReadOnly[]" type cannot be nested g: Required[Required[int]] # E: "Required[]" type cannot be nested h: NotRequired[NotRequired[int]] # E: "NotRequired[]" type cannot be nested j: NotRequired[ReadOnly[Required[ReadOnly[int]]]] # E: "Required[]" type cannot be nested \ # E: "ReadOnly[]" type cannot be nested k: ReadOnly # E: "ReadOnly[]" must have exactly one type argument [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAnnotatedWithSpecialForms] from typing import NotRequired, ReadOnly, Required, TypedDict from typing_extensions import Annotated class A(TypedDict): a: Annotated[NotRequired[ReadOnly[int]], ""] # ok b: NotRequired[ReadOnly[Annotated[int, ""]]] # ok [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictReadOnlyCovariant] from typing import ReadOnly, TypedDict, Union class A(TypedDict): a: ReadOnly[Union[int, str]] class A2(TypedDict): a: ReadOnly[int] class B(TypedDict): a: int class B2(TypedDict): a: Union[int, str] class B3(TypedDict): a: int def fa(a: A) -> None: ... def fa2(a: A2) -> None: ... b: B = {"a": 1} fa(b) fa2(b) b2: B2 = {"a": 1} fa(b2) fa2(b2) # E: Argument 1 to "fa2" has incompatible type "B2"; expected "A2" class C(TypedDict): a: ReadOnly[Union[int, str]] b: Union[str, bytes] class D(TypedDict): a: int b: str d: D = {"a": 1, "b": "x"} c: C = d # E: Incompatible types in assignment (expression has type "D", variable has type "C") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictJoinWithReadOnly] from typing import ReadOnly, TypedDict, TypeVar A = TypedDict('A', {'x': ReadOnly[int]}) B = TypedDict('B', {'x': ReadOnly[int]}, total=False) C = TypedDict('C', {'x': int}) D = TypedDict('D', {'x': int}, total=False) T = TypeVar('T') def j(x: T, y: T) -> T: return x a: A b: B c: C d: D reveal_type(j(a, b)) # N: Revealed type is "TypedDict({'x'?=: builtins.int})" reveal_type(j(b, a)) # N: Revealed type is "TypedDict({'x'?=: builtins.int})" reveal_type(j(a, c)) # N: Revealed type is "TypedDict({'x'=: builtins.int})" reveal_type(j(c, a)) # N: Revealed type is "TypedDict({'x'=: builtins.int})" reveal_type(j(a, d)) # N: Revealed type is "TypedDict({'x'?=: builtins.int})" reveal_type(j(d, a)) # N: Revealed type is "TypedDict({'x'?=: builtins.int})" reveal_type(j(b, c)) # N: Revealed type is "TypedDict({'x'?=: builtins.int})" reveal_type(j(c, b)) # N: Revealed type is "TypedDict({'x'?=: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] # Closed # See https://peps.python.org/pep-0728/ [case testTypedDictWithClosedFalse] from typing import TypedDict D = TypedDict('D', {'x': int, 'y': str}, closed=False) d: D reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.str})" class E(TypedDict, closed=False): x: int y: str e: E reveal_type(e) # N: Revealed type is "TypedDict('__main__.E', {'x': builtins.int, 'y': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictWithClosedTrue] from typing import TypedDict D = TypedDict('D', {'x': int, 'y': str}, closed=True) d: D reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.str}, closed=True)" class E(TypedDict, closed=True): x: int y: str e: E reveal_type(e) # N: Revealed type is "TypedDict('__main__.E', {'x': builtins.int, 'y': builtins.str}, closed=True)" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictWithInvalidClosedArgument] from typing import TypedDict A = TypedDict('A', {'x': int}, closed=0) # E: "closed" argument must be a True or False literal B = TypedDict('B', {'x': int}, closed=bool) # E: "closed" argument must be a True or False literal class C(TypedDict, closed=0): # E: "closed" argument must be a True or False literal x: int class D(TypedDict, closed=bool): # E: "closed" argument must be a True or False literal x: int [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictWithClosedAndTotal] from typing import TypedDict A = TypedDict('A', {'x': int, 'y': str}, total=False, closed=True) B = TypedDict('B', {'x': int, 'y': str}, closed=True, total=False) C = TypedDict('C', {'x': int, 'y': str}, total=True, closed=False) a: A b: B c: C reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {'x'?: builtins.int, 'y'?: builtins.str}, closed=True)" reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'x'?: builtins.int, 'y'?: builtins.str}, closed=True)" reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'x': builtins.int, 'y': builtins.str})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictWithDuplicateKeywordArguments_no_parallel] from typing import TypedDict A = TypedDict('A', {'x': int}, closed=True, closed=False) # E: Repeated keyword argument "closed" for "TypedDict" B = TypedDict('B', {'x': int}, total=True, total=False) # E: Repeated keyword argument "total" for "TypedDict" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictSubclassingClosed] from typing import TypedDict class D(TypedDict, closed=True): x: int y: float d: D reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.float}, closed=True)" class D1(D): pass d1: D1 reveal_type(d1) # N: Revealed type is "TypedDict('__main__.D1', {'x': builtins.int, 'y': builtins.float}, closed=True)" class D2(D, closed=True): pass d2: D2 reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'x': builtins.int, 'y': builtins.float}, closed=True)" class D3(D, closed=False): pass # E: Open TypedDict class cannot subclass closed TypedDict class "D" d3: D3 reveal_type(d3) # N: Revealed type is "TypedDict('__main__.D3', {'x': builtins.int, 'y': builtins.float})" class D4(D): z: int # E: Cannot extend closed base class "D" with new field "z" d4: D4 reveal_type(d4) # N: Revealed type is "TypedDict('__main__.D4', {'x': builtins.int, 'y': builtins.float, 'z': builtins.int}, closed=True)" class D5(D): x: int d5: D5 reveal_type(d5) # N: Revealed type is "TypedDict('__main__.D5', {'x': builtins.int, 'y': builtins.float}, closed=True)" class D6(D): x: float # E: Definition of field "x" incompatible with base class "D" y: int # E: Definition of field "y" incompatible with base class "D" d6: D6 reveal_type(d6) # N: Revealed type is "TypedDict('__main__.D6', {'x': builtins.float, 'y': builtins.int}, closed=True)" class D7(TypedDict, closed=True): x: int z: float class D8(D7, D): # E: Cannot extend closed base class "D7" with field "y" from base class "D" \ # E: Cannot extend closed base class "D" with field "z" from base class "D7" pass d8: D8 reveal_type(d8) # N: Revealed type is "TypedDict('__main__.D8', {'x': builtins.int, 'y': builtins.float, 'z': builtins.float}, closed=True)" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictSubclassingOpenAndClosed] from typing import TypedDict class B1(TypedDict, closed=True): x: int y: float class B2(TypedDict): x: int class D1(B1, B2): pass class D2(B2, B1): pass d1: D1 d2: D2 reveal_type(d1) # N: Revealed type is "TypedDict('__main__.D1', {'x': builtins.int, 'y': builtins.float}, closed=True)" reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'x': builtins.int, 'y': builtins.float}, closed=True)" class B3(TypedDict): z: int class D3(B1, B3): pass # E: Cannot extend closed base class "B1" with field "z" from base class "B3" class D4(B3, B1): pass # E: Cannot extend closed base class "B1" with field "z" from base class "B3" d3: D3 d4: D4 reveal_type(d3) # N: Revealed type is "TypedDict('__main__.D3', {'z': builtins.int, 'x': builtins.int, 'y': builtins.float}, closed=True)" reveal_type(d4) # N: Revealed type is "TypedDict('__main__.D4', {'x': builtins.int, 'y': builtins.float, 'z': builtins.int}, closed=True)" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testCanSubclassClosedTypedDictWithForwardDeclarations] from typing import TypedDict, final class D1(TypedDict, closed=True): forward_declared: "ForwardDeclared" class D2(D1): pass class ForwardDeclared: pass d2: D2 reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'forward_declared': __main__.ForwardDeclared}, closed=True)" [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testTypedDictSubtypingClosedMustRemainClosed] from typing import TypedDict A = TypedDict('A', {'x': int}, closed=True) B = TypedDict('B', {'x': int}, closed=True) C = TypedDict('C', {'x': int}, closed=False) D = TypedDict('D', {'x': int}, closed=False) def f(x: A) -> None: pass def g(x: C) -> None: pass a: A b: B c: C d: D f(b) f(d) # E: Argument 1 to "f" has incompatible type "D"; expected "A" g(d) g(b) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictSubtypingCannotAddKeysToAClosedSupertype] from typing import TypedDict A = TypedDict('A', {'x': int}, closed=True) B = TypedDict('B', {'x': int, 'y': int}, closed=True) C = TypedDict('C', {'x': int}) D = TypedDict('D', {'x': int, 'y': int}) def f(x: A) -> None: pass def g(x: C) -> None: pass b: B d: D f(b) # E: Argument 1 to "f" has incompatible type "B"; expected "A" g(d) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictSubtypingCanDropOptionalReadonlyKeysInAClosedSubtype] from typing import ReadOnly, TypedDict # Optional, readonly, closed: permitted A = TypedDict('A', {'x': int, 'y': ReadOnly[int]}, total=False, closed=True) B = TypedDict('B', {'x': int}, total=False, closed=True) b: B def f_a(x: A) -> None: pass f_a(b) # Optional, readonly, open: not permitted C = TypedDict('C', {'x': int, 'y': ReadOnly[int]}, total=False) D = TypedDict('D', {'x': int}, total=False) d: D def f_c(x: C) -> None: pass f_c(d) # E: Argument 1 to "f_c" has incompatible type "D"; expected "C" # Optional, mutable, closed: not permitted E = TypedDict('E', {'x': int, 'y': int}, total=False, closed=True) F = TypedDict('F', {'x': int}, total=False, closed=True) f: F def f_e(x: E) -> None: pass f_e(f) # E: Argument 1 to "f_e" has incompatible type "F"; expected "E" # Required, readonly, closed: not permitted G = TypedDict('G', {'x': int, 'y': ReadOnly[int]}, closed=True) H = TypedDict('H', {'x': int}, closed=True) h: H def f_g(x: G) -> None: pass f_g(h) # E: Argument 1 to "f_g" has incompatible type "H"; expected "G" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictSubtypingClosedTypeVarBound] from typing import TypedDict, TypeVar A = TypedDict('A', {'x': int}, closed=True) B = TypedDict('B', {'x': int}) TA = TypeVar('TA', bound=A) TB = TypeVar('TB', bound=B) def fA(t: TA) -> TA: return t def fB(t: TB) -> TB: return t a: A b: B fA(a) fA(b) # E: Value of type variable "TA" of "fA" cannot be "B" fB(a) fB(b) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictSubtypingClosedExplicitNever] from typing import NotRequired, ReadOnly, TypedDict from typing_extensions import Never A = TypedDict('A', {}, closed=True) B = TypedDict('B', {'x': NotRequired[Never]}, closed=True) C = TypedDict('C', {'x': ReadOnly[NotRequired[Never]]}, closed=True) def f_a(x: A) -> None: pass def f_b(x: B) -> None: pass def f_c(x: C) -> None: pass a: A b: B c: C # Logically identical types: legal f_a(b) f_b(a) # Subtype allows key removal: legal f_c(a) f_c(b) # Subtype prevents key removal: illegal f_a(c) # E: Argument 1 to "f_a" has incompatible type "C"; expected "A" f_b(c) # E: Argument 1 to "f_b" has incompatible type "C"; expected "B" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testJoinOfClosedTypedDict] from typing import Any, TypedDict, TypeVar A = TypedDict('A', {'x': int}, closed=True) B = TypedDict('B', {'y': int}) C = TypedDict('C', {'y': int}, closed=True) D = TypedDict('D', {'x': int, 'y': int}, closed=True) E = TypedDict('E', {'x': Any, 'y': Any}) T = TypeVar('T') def j(x: T, y: T) -> T: return x a: A b: B c: C d: D e: E reveal_type(j(a, b)) # N: Revealed type is "TypedDict({'y'?=: builtins.int})" reveal_type(j(b, a)) # N: Revealed type is "TypedDict({'y'?=: builtins.int})" reveal_type(j(a, c)) # N: Revealed type is "TypedDict({'x'?=: builtins.int, 'y'?=: builtins.int}, closed=True)" reveal_type(j(c, a)) # N: Revealed type is "TypedDict({'y'?=: builtins.int, 'x'?=: builtins.int}, closed=True)" reveal_type(j(a, d)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y'?=: builtins.int}, closed=True)" reveal_type(j(d, a)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y'?=: builtins.int}, closed=True)" reveal_type(j(a, e)) # N: Revealed type is "TypedDict({'x': Any, 'y'?=: Any})" reveal_type(j(e, a)) # N: Revealed type is "TypedDict({'x': Any, 'y'?=: Any})" reveal_type(j(b, e)) # N: Revealed type is "TypedDict({'y': Any})" reveal_type(j(e, b)) # N: Revealed type is "TypedDict({'y': Any})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfClosedTypedDictsWithMatchingRequiredKeysIsNotAnonymous] from typing import TypedDict, TypeVar, Callable X = TypedDict('X', {'x': int, 'y': int}, closed=True) Y = TypedDict('Y', {'x': int, 'y': int}, closed=True) Z = TypedDict('Z', {'x': int, 'y': int}) T = TypeVar('T') def meet(x: Callable[[T, T], None]) -> T: pass def fXY(x: X, y: Y) -> None: pass def fYX(x: Y, y: X) -> None: pass def fXZ(x: X, y: Z) -> None: pass def fZX(x: Z, y: X) -> None: pass reveal_type(meet(fXY)) # N: Revealed type is "TypedDict('__main__.X', {'x': builtins.int, 'y': builtins.int}, closed=True)" reveal_type(meet(fYX)) # N: Revealed type is "TypedDict('__main__.Y', {'x': builtins.int, 'y': builtins.int}, closed=True)" reveal_type(meet(fXZ)) # N: Revealed type is "TypedDict('__main__.X', {'x': builtins.int, 'y': builtins.int}, closed=True)" reveal_type(meet(fZX)) # N: Revealed type is "TypedDict('__main__.X', {'x': builtins.int, 'y': builtins.int}, closed=True)" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfClosedTypedDictsWithDifferentKeys] from typing import TypedDict, TypeVar, Callable, ReadOnly T = TypeVar('T') def meet(x: Callable[[T, T], None]) -> T: pass A = TypedDict('A', {'a': int}, closed=True) B = TypedDict('B', {'b': int}, closed=True) def fAB(x: A, y: B) -> None: pass if int(): reveal_type(meet(fAB)) # N: Revealed type is "Never" C = TypedDict('C', {'c': int}, closed=True, total=False) D = TypedDict('D', {'d': int}, closed=True, total=False) def fCD(x: C, y: D) -> None: pass if int(): reveal_type(meet(fCD)) # N: Revealed type is "Never" E = TypedDict('E', {'e': ReadOnly[int]}, closed=True) F = TypedDict('F', {'f': ReadOnly[int]}, closed=True) def fEF(x: E, y: F) -> None: pass if int(): reveal_type(meet(fEF)) # N: Revealed type is "Never" G = TypedDict('G', {'g': ReadOnly[int]}, closed=True, total=False) H = TypedDict('H', {'h': ReadOnly[int]}, closed=True, total=False) def fAH(x: A, y: H) -> None: pass if int(): reveal_type(meet(fAH)) # N: Revealed type is "Never" def fCH(x: C, y: H) -> None: pass if int(): reveal_type(meet(fCH)) # N: Revealed type is "Never" def fEH(x: E, y: H) -> None: pass if int(): reveal_type(meet(fEH)) # N: Revealed type is "Never" def fGH(x: G, y: H) -> None: pass if int(): reveal_type(meet(fGH)) # N: Revealed type is "TypedDict({}, closed=True)" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsExplicitAndImplicitClosedMissing] from typing import Any, NotRequired, ReadOnly, TypedDict, TypeVar, Callable from typing_extensions import Never A = TypedDict('A', {'x': ReadOnly[NotRequired[Never]]}, closed=True) B = TypedDict('B', {'y': ReadOnly[NotRequired[Never]]}, closed=True) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: A, y: B) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({}, closed=True)" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictClosedMissingAndAny] from typing import Any, TypedDict, TypeVar, Callable, ReadOnly T = TypeVar('T') def meet(x: Callable[[T, T], None]) -> T: pass A = TypedDict('A', {}, closed=True) B = TypedDict('B', {'x': Any}) C = TypedDict('C', {'x': Any}, total=False) def fAB(x: A, y: B) -> None: pass def fBA(x: B, y: A) -> None: pass def fAC(x: A, y: C) -> None: pass def fCA(x: C, y: A) -> None: pass if int(): reveal_type(meet(fAB)) # N: Revealed type is "Never" if int(): reveal_type(meet(fBA)) # N: Revealed type is "Never" reveal_type(meet(fAC)) # N: Revealed type is "TypedDict({}, closed=True)" reveal_type(meet(fCA)) # N: Revealed type is "TypedDict({}, closed=True)" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfTypedDictsClosedNotRequiredNeverAndAny] from typing import Any, NotRequired, TypedDict, TypeVar, Callable from typing_extensions import Never A = TypedDict('A', {'x': NotRequired[Any], 'y': NotRequired[Never]}, closed=True) B = TypedDict('B', {'x': NotRequired[Never], 'y': NotRequired[Any]}, closed=True) T = TypeVar('T') def f(x: Callable[[T, T], None]) -> T: pass def g(x: A, y: B) -> None: pass reveal_type(f(g)) # N: Revealed type is "TypedDict({}, closed=True)" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfOpenAndClosedTypedDictsExtraKeyInClosed] from typing import TypedDict, TypeVar, Callable, ReadOnly T = TypeVar('T') def meet(x: Callable[[T, T], None]) -> T: pass Ax = TypedDict('Ax', {'a': ReadOnly[float]}) AyB = TypedDict('AyB', {'a': ReadOnly[int], 'b': int}, closed=True) def fAxAyB(x: Ax, y: AyB) -> None: pass def fAyBAx(x: AyB, y: Ax) -> None: pass reveal_type(meet(fAxAyB)) # N: Revealed type is "TypedDict({'a'=: builtins.int, 'b': builtins.int}, closed=True)" reveal_type(meet(fAyBAx)) # N: Revealed type is "TypedDict({'a'=: builtins.int, 'b': builtins.int}, closed=True)" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testMeetOfOpenAndClosedTypedDictsExtraKeyInOpen] from typing import TypedDict, TypeVar, Callable, ReadOnly T = TypeVar('T') def meet(x: Callable[[T, T], None]) -> T: pass C = TypedDict('C', {'a': ReadOnly[float]}, closed=True) D1 = TypedDict('D1', {'a': ReadOnly[int], 'b': int}) D2 = TypedDict('D2', {'a': ReadOnly[int], 'b': ReadOnly[int]}) D3 = TypedDict('D3', {'a': ReadOnly[int], 'b': int}, total=False) D4 = TypedDict('D4', {'a': ReadOnly[int], 'b': ReadOnly[int]}, total=False) def fCD1(x: C, y: D1) -> None: pass def fD1C(x: D1, y: C) -> None: pass def fCD2(x: C, y: D2) -> None: pass def fD2C(x: D2, y: C) -> None: pass def fCD3(x: C, y: D3) -> None: pass def fD3C(x: D3, y: C) -> None: pass def fCD4(x: C, y: D4) -> None: pass def fD4C(x: D4, y: C) -> None: pass if int(): reveal_type(meet(fCD1)) # N: Revealed type is "Never" if int(): reveal_type(meet(fD1C)) # N: Revealed type is "Never" if int(): reveal_type(meet(fCD2)) # N: Revealed type is "Never" if int(): reveal_type(meet(fD2C)) # N: Revealed type is "Never" if int(): reveal_type(meet(fCD3)) # N: Revealed type is "Never" if int(): reveal_type(meet(fD3C)) # N: Revealed type is "Never" reveal_type(meet(fCD4)) # N: Revealed type is "TypedDict({'a'=: builtins.int}, closed=True)" reveal_type(meet(fD4C)) # N: Revealed type is "TypedDict({'a'=: builtins.int}, closed=True)" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictGetMethodClosed] from typing import TypedDict, Literal class Unrelated: pass D = TypedDict('D', {'x': int, 'y': str}, closed=True) d: D u: Unrelated x: Literal['x'] y: Literal['y'] z: Literal['z'] x_or_y: Literal['x', 'y'] x_or_z: Literal['x', 'z'] x_or_y_or_z: Literal['x', 'y', 'z'] # test with literal expression reveal_type(d.get('x')) # N: Revealed type is "builtins.int" reveal_type(d.get('y')) # N: Revealed type is "builtins.str" reveal_type(d.get('z')) # N: Revealed type is "None" reveal_type(d.get('z', u)) # N: Revealed type is "__main__.Unrelated" # test with literal type / union of literal types with implicit default reveal_type(d.get(x)) # N: Revealed type is "builtins.int" reveal_type(d.get(y)) # N: Revealed type is "builtins.str" reveal_type(d.get(z)) # N: Revealed type is "None" reveal_type(d.get(x_or_y)) # N: Revealed type is "builtins.int | builtins.str" reveal_type(d.get(x_or_z)) # N: Revealed type is "builtins.int | None" reveal_type(d.get(x_or_y_or_z)) # N: Revealed type is "builtins.int | builtins.str | None" # test with literal type / union of literal types with explicit default reveal_type(d.get(x, u)) # N: Revealed type is "builtins.int" reveal_type(d.get(y, u)) # N: Revealed type is "builtins.str" reveal_type(d.get(z, u)) # N: Revealed type is "__main__.Unrelated" reveal_type(d.get(x_or_y, u)) # N: Revealed type is "builtins.int | builtins.str" reveal_type(d.get(x_or_z, u)) # N: Revealed type is "builtins.int | __main__.Unrelated" reveal_type(d.get(x_or_y_or_z, u)) # N: Revealed type is "builtins.int | builtins.str | __main__.Unrelated" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testOperatorContainsNarrowsTypedDicts_unionWithList_closed] from __future__ import annotations from typing import assert_type, TypedDict, Union class D(TypedDict, closed=True): foo: int d_or_list: D | list[str] if 'foo' in d_or_list: assert_type(d_or_list, Union[D, list[str]]) elif 'bar' in d_or_list: assert_type(d_or_list, list[str]) else: assert_type(d_or_list, list[str]) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_total_closed] from __future__ import annotations from typing import assert_type, Literal, TypedDict, TypeVar, Union class D1(TypedDict, closed=True): foo: int class D2(TypedDict, closed=True): bar: int d: D1 | D2 if 'foo' in d: assert_type(d, D1) else: assert_type(d, D2) foo_or_bar: Literal['foo', 'bar'] if foo_or_bar in d: assert_type(d, Union[D1, D2]) else: assert_type(d, Union[D1, D2]) foo_or_invalid: Literal['foo', 'invalid'] if foo_or_invalid in d: assert_type(d, D1) # won't narrow 'foo_or_invalid' assert_type(foo_or_invalid, Literal['foo', 'invalid']) else: assert_type(d, Union[D1, D2]) # won't narrow 'foo_or_invalid' assert_type(foo_or_invalid, Literal['foo', 'invalid']) TD = TypeVar('TD', D1, D2) def f(arg: TD) -> None: value: int if 'foo' in arg: assert_type(arg['foo'], int) else: assert_type(arg['bar'], int) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_closed] # flags: --warn-unreachable from __future__ import annotations from typing import assert_type, TypedDict, Union class DClosed(TypedDict, closed=True): foo: int class DNotClosed(TypedDict): bar: int d_not_closed: DNotClosed if 'bar' in d_not_closed: assert_type(d_not_closed, DNotClosed) else: spam = 'ham' # E: Statement is unreachable if 'spam' in d_not_closed: assert_type(d_not_closed, DNotClosed) else: assert_type(d_not_closed, DNotClosed) d_closed: DClosed if 'spam' in d_closed: spam = 'ham' # E: Statement is unreachable else: assert_type(d_closed, DClosed) d_union: DClosed | DNotClosed if 'foo' in d_union: assert_type(d_union, Union[DClosed, DNotClosed]) else: assert_type(d_union, DNotClosed) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_partialThroughTotalFalse_closed] from __future__ import annotations from typing import assert_type, Literal, TypedDict, Union class DTotal(TypedDict, closed=True): required_key: int class DNotTotal(TypedDict, total=False, closed=True): optional_key: int d: DTotal | DNotTotal if 'required_key' in d: assert_type(d, DTotal) else: assert_type(d, DNotTotal) if 'optional_key' in d: assert_type(d, DNotTotal) else: assert_type(d, Union[DTotal, DNotTotal]) key: Literal['optional_key', 'required_key'] if key in d: assert_type(d, Union[DTotal, DNotTotal]) else: assert_type(d, Union[DTotal, DNotTotal]) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypedDicts_partialThroughNotRequired_closed] from __future__ import annotations from typing import assert_type, TypedDict, Union from typing_extensions import Required, NotRequired class D1(TypedDict, closed=True): required_key: Required[int] optional_key: NotRequired[int] class D2(TypedDict, closed=True): abc: int xyz: int d: D1 | D2 if 'required_key' in d: assert_type(d, D1) else: assert_type(d, D2) if 'optional_key' in d: assert_type(d, D1) else: assert_type(d, Union[D1, D2]) [builtins fixtures/dict.pyi] [typing fixtures/typing-full.pyi] [case testOperatorContainsNarrowsTypeVarWithClosedTypedDictBound] from typing import TypedDict, TypeVar from typing_extensions import Never, assert_type T = TypeVar('T', bound='D') class D(TypedDict, closed=True): a: int def func(t: T): if "b" in t: assert_type(t, Never) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackFromClosedMissingKey] # flags: --extra-checks from typing import TypedDict from typing_extensions import Never, NotRequired D1 = TypedDict("D1", {"a": int, "b": str}, closed=True) D2 = TypedDict("D2", {"a": int, "b": str, "c": int}) D3 = TypedDict("D3", {"a": int, "b": str, "c": NotRequired[int]}) d1: D1 d2: D2 = {**d1} # E: Missing key "c" for TypedDict "D2" d3: D3 = {**d1} [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackIntoClosed] # flags: --extra-checks from typing import Any, Mapping, TypedDict, Union from typing_extensions import Never, NotRequired D1 = TypedDict("D1", {"a": int, "b": str}, closed=True) D2 = TypedDict("D2", {"a": int, "b": str}) D3 = TypedDict("D3", {"c": int, "d": str}, closed=True) D4 = TypedDict("D4", {"c": int, "d": str}) D5 = TypedDict("D5", {"a": int, "b": str, "c": int, "d": str}, closed=True) d1: D1 d2: D2 d3: D3 d4: D4 d5: D5 m: Mapping[Any, Any] u34: Union[D3, D4] u35: Union[D3, D5] u5m: Union[D5, Mapping[Any, Any]] d5 = {**d1, **d3} d5 = { **d1, **d4, # E: Cannot unpack item that may contain extra keys into a closed TypedDict } d5 = { **d2, # E: Cannot unpack item that may contain extra keys into a closed TypedDict **d3, } d5 = { **d1, **u34, # E: Cannot unpack item that may contain extra keys into a closed TypedDict } d5 = {**d1, **u35} d5 = { **m, # E: Cannot unpack item that may contain extra keys into a closed TypedDict **d5, } d5 = { **u5m, # E: Cannot unpack item that may contain extra keys into a closed TypedDict } [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictFinalAndClassVar] from typing import TypedDict, Final, ClassVar class My(TypedDict): a: Final # E: Final[...] can't be used inside a TypedDict b: Final[int] # E: Final[...] can't be used inside a TypedDict c: ClassVar # E: ClassVar[...] can't be used inside a TypedDict d: ClassVar[int] # E: ClassVar[...] can't be used inside a TypedDict Func = TypedDict('Func', { 'a': Final, # E: Final[...] can't be used inside a TypedDict 'b': Final[int], # E: Final[...] can't be used inside a TypedDict 'c': ClassVar, # E: ClassVar[...] can't be used inside a TypedDict 'd': ClassVar[int], # E: ClassVar[...] can't be used inside a TypedDict }) [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictNestedInClassAndInherited] from typing import TypedDict class Base: class Params(TypedDict): name: str class Derived(Base): pass class DerivedOverride(Base): class Params(Base.Params): pass Base.Params(name="Robert") Derived.Params(name="Robert") DerivedOverride.Params(name="Robert") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testEnumAsClassMemberNoCrash] # https://github.com/python/mypy/issues/18736 from typing import TypedDict class Base: def __init__(self, namespace: dict[str, str]) -> None: # Not a bug: trigger defer names = {n: n for n in namespace if fail} # E: Name "fail" is not defined self.d = TypedDict("d", names) # E: TypedDict type as attribute is not supported \ # E: TypedDict() expects a dictionary literal as the second argument [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAlias] from typing import NotRequired, TypedDict from typing_extensions import TypeAlias class Base(TypedDict): foo: int Base1 = Base class Child1(Base1): bar: NotRequired[int] c11: Child1 = {"foo": 0} c12: Child1 = {"foo": 0, "bar": 1} c13: Child1 = {"foo": 0, "bar": 1, "baz": "error"} # E: Extra key "baz" for TypedDict "Child1" Base2: TypeAlias = Base class Child2(Base2): bar: NotRequired[int] c21: Child2 = {"foo": 0} c22: Child2 = {"foo": 0, "bar": 1} c23: Child2 = {"foo": 0, "bar": 1, "baz": "error"} # E: Extra key "baz" for TypedDict "Child2" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAliasInheritance] from typing import TypedDict from typing_extensions import TypeAlias class A(TypedDict): x: str class B(TypedDict): y: int B1 = B B2: TypeAlias = B class C(A, B1): pass c1: C = {"y": 1} # E: Missing key "x" for TypedDict "C" c2: C = {"x": "x", "y": 2} c3: C = {"x": 1, "y": 2} # E: Incompatible types (expression has type "int", TypedDict item "x" has type "str") class D(A, B2): pass d1: D = {"y": 1} # E: Missing key "x" for TypedDict "D" d2: D = {"x": "x", "y": 2} d3: D = {"x": 1, "y": 2} # E: Incompatible types (expression has type "int", TypedDict item "x" has type "str") [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAliasDuplicateBases] from typing import TypedDict from typing_extensions import TypeAlias class A(TypedDict): x: str A1 = A A2 = A A3: TypeAlias = A class E(A1, A2): pass # E: Duplicate base class "A" class F(A1, A3): pass # E: Duplicate base class "A" class G(A, A1): pass # E: Duplicate base class "A" class H(A, list): pass # E: All bases of a new TypedDict must be TypedDict types [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAliasGeneric] from typing import Generic, TypedDict, TypeVar from typing_extensions import TypeAlias _T = TypeVar("_T") class A(Generic[_T], TypedDict): x: _T # This is by design - no_args aliases are only supported for instances A0 = A class B(A0[str]): # E: Bad number of arguments for type alias, expected 0, given 1 y: int A1 = A[_T] A2: TypeAlias = A[_T] Aint = A[int] class C(A1[_T]): y: str c1: C[int] = {"x": 0, "y": "a"} c2: C[int] = {"x": "no", "y": "a"} # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") class D(A2[_T]): y: str d1: D[int] = {"x": 0, "y": "a"} d2: D[int] = {"x": "no", "y": "a"} # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") class E(Aint): y: str e1: E = {"x": 0, "y": "a"} e2: E = {"x": "no", "y": "a"} [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAliasAsInstanceAttribute] from typing import TypedDict class Dicts: class TF(TypedDict, total=False): user_id: int TotalFalse = TF dicts = Dicts() reveal_type(dicts.TF) # N: Revealed type is "def (*, user_id: builtins.int =) -> TypedDict('__main__.Dicts.TF', {'user_id'?: builtins.int})" reveal_type(dicts.TotalFalse) # N: Revealed type is "def (*, user_id: builtins.int =) -> TypedDict('__main__.Dicts.TF', {'user_id'?: builtins.int})" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testRecursiveNestedTypedDictInference] from typing import TypedDict, Sequence from typing_extensions import NotRequired class Component(TypedDict): type: str components: NotRequired[Sequence['Component']] inputs: Sequence[Component] = [{ 'type': 'tuple', 'components': [ {'type': 'uint256'}, {'type': 'address'}, ] }] [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictAssignableToWiderContext] from typing import TypedDict, Union class TD(TypedDict): x: int x: Union[TD, dict[str, str]] = {"x": "foo"} y: Union[TD, dict[str, int]] = {"x": "foo"} # E: Dict entry 0 has incompatible type "str": "str"; expected "str": "int" def ok(d: Union[TD, dict[str, str]]) -> None: ... ok({"x": "foo"}) def bad(d: Union[TD, dict[str, int]]) -> None: ... bad({"x": "foo"}) # E: Dict entry 0 has incompatible type "str": "str"; expected "str": "int" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] [case testTypedDictUnpackImportCycle] import mre [file mre.py] from mre_pkg.model import Callback Callback(callback=1) # E: Argument "callback" to "Callback" has incompatible type "int"; expected "Callback" [file mre_pkg/model.pyi] from typing_extensions import Unpack, TYPE_CHECKING, TypedDict from .callbacks import Callback as Callback class _ModelInit(TypedDict, total=False): callback: Callback class Model: def __init__(self, **kwargs: Unpack[_ModelInit]) -> None: ... [file mre_pkg/callbacks.pyi] from typing_extensions import Unpack, TYPE_CHECKING, TypedDict from .model import Model, _ModelInit class _CallbackInit(_ModelInit, total=False): ... class Callback(Model): def __init__(self, **kwargs: Unpack[_CallbackInit]) -> None: ... [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi]