Debian Codegraph @

test-data/unit/check-typeddict.test

raw
1 -- Create Instance
2
3 [case testCanCreateTypedDictInstanceWithKeywordArguments]
4 from typing import TypedDict
5 Point = TypedDict('Point', {'x': int, 'y': int})
6 p = Point(x=42, y=1337)
7 reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})"
8 # Use values() to check fallback value type.
9 reveal_type(p.values()) # N: Revealed type is "typing.Iterable[builtins.object]"
10 [builtins fixtures/dict.pyi]
11 [typing fixtures/typing-typeddict.pyi]
12 [targets __main__]
13
14 [case testCanCreateTypedDictInstanceWithDictCall]
15 from typing import TypedDict
16 Point = TypedDict('Point', {'x': int, 'y': int})
17 p = Point(dict(x=42, y=1337))
18 reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})"
19 # Use values() to check fallback value type.
20 reveal_type(p.values()) # N: Revealed type is "typing.Iterable[builtins.object]"
21 [builtins fixtures/dict.pyi]
22 [typing fixtures/typing-typeddict.pyi]
23
24 [case testCanCreateTypedDictInstanceWithDictLiteral]
25 from typing import TypedDict
26 Point = TypedDict('Point', {'x': int, 'y': int})
27 p = Point({'x': 42, 'y': 1337})
28 reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})"
29 # Use values() to check fallback value type.
30 reveal_type(p.values()) # N: Revealed type is "typing.Iterable[builtins.object]"
31 [builtins fixtures/dict.pyi]
32 [typing fixtures/typing-typeddict.pyi]
33
34 [case testCanCreateTypedDictInstanceWithNoArguments]
35 from typing import TypedDict, TypeVar, Union
36 EmptyDict = TypedDict('EmptyDict', {})
37 p = EmptyDict()
38 reveal_type(p) # N: Revealed type is "TypedDict('__main__.EmptyDict', {})"
39 reveal_type(p.values()) # N: Revealed type is "typing.Iterable[builtins.object]"
40 [builtins fixtures/dict.pyi]
41 [typing fixtures/typing-typeddict.pyi]
42
43
44 -- Create Instance (Errors)
45
46 [case testCannotCreateTypedDictInstanceWithUnknownArgumentPattern]
47 from typing import TypedDict
48 Point = TypedDict('Point', {'x': int, 'y': int})
49 p = Point(42, 1337) # E: Expected keyword arguments, {...}, or dict(...) in TypedDict constructor
50 [builtins fixtures/dict.pyi]
51 [typing fixtures/typing-typeddict.pyi]
52
53 [case testCannotCreateTypedDictInstanceNonLiteralItemName]
54 from typing import TypedDict
55 Point = TypedDict('Point', {'x': int, 'y': int})
56 x = 'x'
57 p = Point({x: 42, 'y': 1337}) # E: Expected TypedDict key to be string literal
58 [builtins fixtures/dict.pyi]
59 [typing fixtures/typing-typeddict.pyi]
60
61 [case testCannotCreateTypedDictInstanceWithExtraItems]
62 from typing import TypedDict
63 Point = TypedDict('Point', {'x': int, 'y': int})
64 p = Point(x=42, y=1337, z=666) # E: Extra key "z" for TypedDict "Point"
65 [builtins fixtures/dict.pyi]
66 [typing fixtures/typing-typeddict.pyi]
67
68 [case testCannotCreateTypedDictInstanceWithMissingItems]
69 from typing import TypedDict
70 Point = TypedDict('Point', {'x': int, 'y': int})
71 p = Point(x=42) # E: Missing key "y" for TypedDict "Point"
72 [builtins fixtures/dict.pyi]
73 [typing fixtures/typing-typeddict.pyi]
74
75 [case testCannotCreateTypedDictInstanceWithIncompatibleItemType]
76 from typing import TypedDict
77 Point = TypedDict('Point', {'x': int, 'y': int})
78 p = Point(x='meaning_of_life', y=1337) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
79 [builtins fixtures/dict.pyi]
80 [typing fixtures/typing-typeddict.pyi]
81
82 [case testCannotCreateTypedDictInstanceWithInlineTypedDict]
83 from typing import TypedDict
84 D = TypedDict('D', {
85 'x': TypedDict('E', { # E: Use dict literal for nested TypedDict
86 'y': int
87 })
88 })
89 [builtins fixtures/dict.pyi]
90 [typing fixtures/typing-typeddict.pyi]
91
92 -- Define TypedDict (Class syntax)
93
94 [case testCanCreateTypedDictWithClass]
95 from typing import TypedDict
96
97 class Point(TypedDict):
98 x: int
99 y: int
100
101 p = Point(x=42, y=1337)
102 reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})"
103 [builtins fixtures/dict.pyi]
104 [typing fixtures/typing-typeddict.pyi]
105
106 [case testCanCreateTypedDictWithSubclass]
107 from typing import TypedDict
108
109 class Point1D(TypedDict):
110 x: int
111 class Point2D(Point1D):
112 y: int
113 r: Point1D
114 p: Point2D
115 reveal_type(r) # N: Revealed type is "TypedDict('__main__.Point1D', {'x': builtins.int})"
116 reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point2D', {'x': builtins.int, 'y': builtins.int})"
117 [builtins fixtures/dict.pyi]
118 [typing fixtures/typing-typeddict.pyi]
119
120 [case testCanCreateTypedDictWithSubclass2]
121 from typing import TypedDict
122
123 class Point1D(TypedDict):
124 x: int
125 class Point2D(TypedDict, Point1D): # We also allow to include TypedDict in bases, it is simply ignored at runtime
126 y: int
127
128 p: Point2D
129 reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point2D', {'x': builtins.int, 'y': builtins.int})"
130 [builtins fixtures/dict.pyi]
131 [typing fixtures/typing-typeddict.pyi]
132
133 [case testCanCreateTypedDictClassEmpty]
134 from typing import TypedDict
135
136 class EmptyDict(TypedDict):
137 pass
138
139 p = EmptyDict()
140 reveal_type(p) # N: Revealed type is "TypedDict('__main__.EmptyDict', {})"
141 [builtins fixtures/dict.pyi]
142 [typing fixtures/typing-typeddict.pyi]
143
144
145 [case testCanCreateTypedDictWithClassFunctionBases]
146 # Test that we can use class-syntax to merge function-based TypedDicts
147 from typing import TypedDict
148
149 MovieBase1 = TypedDict(
150 'MovieBase1', {'name': str, 'year': int})
151 MovieBase2 = TypedDict(
152 'MovieBase2', {'based_on': str}, total=False)
153
154 class Movie(MovieBase1, MovieBase2):
155 pass
156
157 def foo(x):
158 # type: (Movie) -> None
159 pass
160
161 foo({}) # E: Missing keys ("name", "year") for TypedDict "Movie"
162 foo({'name': 'lol', 'year': 2009, 'based_on': 0}) # E: Incompatible types (expression has type "int", TypedDict item "based_on" has type "str")
163 [builtins fixtures/dict.pyi]
164 [typing fixtures/typing-typeddict.pyi]
165
166 -- Define TypedDict (Class syntax errors)
167
168 [case testCannotCreateTypedDictWithClassOtherBases]
169 from typing import TypedDict
170
171 class A: pass
172
173 class Point1D(TypedDict, A): # E: All bases of a new TypedDict must be TypedDict types
174 x: int
175 class Point2D(Point1D, A): # E: All bases of a new TypedDict must be TypedDict types
176 y: int
177
178 p: Point2D
179 reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point2D', {'x': builtins.int, 'y': builtins.int})"
180 [builtins fixtures/dict.pyi]
181 [typing fixtures/typing-typeddict.pyi]
182
183 [case testCannotCreateTypedDictWithDuplicateBases]
184 # https://github.com/python/mypy/issues/3673
185 from typing import TypedDict
186
187 class A(TypedDict):
188 x: str
189 y: int
190
191 class B(A, A): # E: Duplicate base class "A"
192 z: str
193
194 class C(TypedDict, TypedDict): # E: Duplicate base class "TypedDict"
195 c1: int
196 [typing fixtures/typing-typeddict.pyi]
197
198 [case testCannotCreateTypedDictWithClassWithOtherStuff]
199 from typing import TypedDict
200
201 class Point(TypedDict):
202 x: int
203 y: int = 1 # E: Right hand side values are not supported in TypedDict
204 def f(): pass # E: Invalid statement in TypedDict definition; expected "field_name: field_type"
205 z = int # E: Invalid statement in TypedDict definition; expected "field_name: field_type"
206
207 p = Point(x=42, y=1337, z='whatever')
208 reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int, 'z': Any})"
209 [builtins fixtures/dict.pyi]
210 [typing fixtures/typing-typeddict.pyi]
211
212 [case testCannotCreateTypedDictWithClassWithFunctionUsedToCrash]
213 # https://github.com/python/mypy/issues/11079
214 from typing import TypedDict
215 class D(TypedDict):
216 y: int
217 def x(self, key: int): # E: Invalid statement in TypedDict definition; expected "field_name: field_type"
218 pass
219
220 d = D(y=1)
221 reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'y': builtins.int})"
222 [builtins fixtures/dict.pyi]
223 [typing fixtures/typing-typeddict.pyi]
224
225 [case testCannotCreateTypedDictWithDecoratedFunction]
226 # flags: --disallow-any-expr
227 # https://github.com/python/mypy/issues/13066
228 from typing import TypedDict
229 class D(TypedDict):
230 @classmethod # E: Invalid statement in TypedDict definition; expected "field_name: field_type"
231 def m(self) -> D:
232 pass
233 d = D()
234 reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {})"
235 [builtins fixtures/dict.pyi]
236 [typing fixtures/typing-typeddict.pyi]
237
238 [case testTypedDictDecoratorUndefinedNames]
239 from typing import TypedDict
240
241 @abc # E: Name "abc" is not defined
242 @efg.hij # E: Name "efg" is not defined
243 @klm[nop] # E: Name "klm" is not defined \
244 # E: Name "nop" is not defined
245 @qrs.tuv[wxy] # E: Name "qrs" is not defined \
246 # E: Name "wxy" is not defined
247 class A(TypedDict):
248 x: int
249 [builtins fixtures/dict.pyi]
250 [typing fixtures/typing-typeddict.pyi]
251
252 [case testTypedDictWithClassmethodAlternativeConstructorDoesNotCrash]
253 # https://github.com/python/mypy/issues/5653
254 from typing import TypedDict
255
256 class Foo(TypedDict):
257 bar: str
258 @classmethod # E: Invalid statement in TypedDict definition; expected "field_name: field_type"
259 def baz(cls) -> "Foo": ...
260 [builtins fixtures/dict.pyi]
261 [typing fixtures/typing-typeddict.pyi]
262
263 [case testCanCreateTypedDictTypeWithUnderscoreItemName]
264 from typing import TypedDict
265 Point = TypedDict('Point', {'x': int, 'y': int, '_fallback': object})
266 [builtins fixtures/dict.pyi]
267 [typing fixtures/typing-typeddict.pyi]
268
269 [case testCanCreateTypedDictWithClassUnderscores]
270 from typing import TypedDict
271
272 class Point(TypedDict):
273 x: int
274 _y: int
275
276 p: Point
277 reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, '_y': builtins.int})"
278 [builtins fixtures/dict.pyi]
279 [typing fixtures/typing-typeddict.pyi]
280
281 [case testCannotCreateTypedDictWithDuplicateKey1]
282 from typing import TypedDict
283
284 class Bad(TypedDict):
285 x: int
286 x: str # E: Duplicate TypedDict key "x"
287
288 b: Bad
289 reveal_type(b) # N: Revealed type is "TypedDict('__main__.Bad', {'x': builtins.int})"
290 [builtins fixtures/dict.pyi]
291 [typing fixtures/typing-typeddict.pyi]
292
293 [case testCannotCreateTypedDictWithDuplicateKey2]
294 from typing import TypedDict
295
296 D1 = TypedDict("D1", {
297 "x": int,
298 "x": int, # E: Duplicate TypedDict key "x"
299 })
300 D2 = TypedDict("D2", {"x": int, "x": str}) # E: Duplicate TypedDict key "x"
301
302 d1: D1
303 d2: D2
304 reveal_type(d1) # N: Revealed type is "TypedDict('__main__.D1', {'x': builtins.int})"
305 reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'x': builtins.str})"
306 [builtins fixtures/dict.pyi]
307 [typing fixtures/typing-typeddict.pyi]
308
309 [case testCanCreateTypedDictWithClassOverwriting]
310 from typing import TypedDict
311
312 class Point1(TypedDict):
313 x: int
314 class Point2(TypedDict):
315 x: float
316 class Bad(Point1, Point2): # E: Incompatible definitions of field "x" in base classes "Point2" and "Point1"
317 pass
318
319 b: Bad
320 reveal_type(b) # N: Revealed type is "TypedDict('__main__.Bad', {'x': builtins.int})"
321 [builtins fixtures/dict.pyi]
322 [typing fixtures/typing-typeddict.pyi]
323
324 [case testCanCreateTypedDictWithClassOverwriting2]
325 from typing import TypedDict
326
327 class Point1(TypedDict):
328 x: int
329 class Point2(Point1):
330 x: float # E: Definition of field "x" incompatible with base class "Point1"
331
332 p2: Point2
333 reveal_type(p2) # N: Revealed type is "TypedDict('__main__.Point2', {'x': builtins.float})"
334 [builtins fixtures/dict.pyi]
335 [typing fixtures/typing-typeddict.pyi]
336
337 [case testCanCreateTypedDictWithClassOverwriting3]
338 from typing import TypedDict
339
340 class Point1(TypedDict):
341 x: float
342 class Point2(Point1):
343 x: int # E: Definition of field "x" incompatible with base class "Point1"
344
345 p2: Point2
346 reveal_type(p2) # N: Revealed type is "TypedDict('__main__.Point2', {'x': builtins.int})"
347 [builtins fixtures/dict.pyi]
348 [typing fixtures/typing-typeddict.pyi]
349
350 [case testCanCreateTypedDictWithClassOverwriting4]
351 from typing import TypedDict
352
353 class Point1(TypedDict):
354 x: int
355 class Point2(TypedDict, total=False):
356 x: int
357 class Bad(Point1, Point2): # E: Field "x" is required in base class "Point1" but can be deleted in base class "Point2"
358 pass
359
360 b: Bad
361 reveal_type(b) # N: Revealed type is "TypedDict('__main__.Bad', {'x': builtins.int})"
362 [builtins fixtures/dict.pyi]
363 [typing fixtures/typing-typeddict.pyi]
364
365 [case testCanCreateTypedDictWithClassOverwriting5]
366 from typing import TypedDict
367
368 class Point1(TypedDict):
369 x: int
370 class Point2(Point1, total=False):
371 x: int # E: Field "x" is required in base class "Point1"
372
373 p2: Point2
374 reveal_type(p2) # N: Revealed type is "TypedDict('__main__.Point2', {'x'?: builtins.int})"
375 [builtins fixtures/dict.pyi]
376 [typing fixtures/typing-typeddict.pyi]
377
378 [case testCanCreateTypedDictWithClassOverwriting6]
379 from typing import TypedDict
380
381 class Point1(TypedDict, total=False):
382 x: int
383 class Point2(TypedDict):
384 x: int
385 class Bad(Point1, Point2): # E: Field "x" is required in base class "Point2" but can be deleted in base class "Point1"
386 pass
387
388 b: Bad
389 reveal_type(b) # N: Revealed type is "TypedDict('__main__.Bad', {'x'?: builtins.int})"
390 [builtins fixtures/dict.pyi]
391 [typing fixtures/typing-typeddict.pyi]
392
393 [case testCanCreateTypedDictWithClassOverwriting7]
394 from typing import TypedDict
395
396 class Point1(TypedDict, total=False):
397 x: int
398 class Point2(Point1):
399 x: int # E: Field "x" can be deleted in base class "Point1"
400
401 p2: Point2
402 reveal_type(p2) # N: Revealed type is "TypedDict('__main__.Point2', {'x': builtins.int})"
403 [builtins fixtures/dict.pyi]
404 [typing fixtures/typing-typeddict.pyi]
405
406
407 -- Subtyping
408
409 [case testCanConvertTypedDictToItself]
410 from typing import TypedDict
411 Point = TypedDict('Point', {'x': int, 'y': int})
412 def identity(p: Point) -> Point:
413 return p
414 [builtins fixtures/dict.pyi]
415 [typing fixtures/typing-typeddict.pyi]
416
417 [case testCanConvertTypedDictToEquivalentTypedDict]
418 from typing import TypedDict
419 PointA = TypedDict('PointA', {'x': int, 'y': int})
420 PointB = TypedDict('PointB', {'x': int, 'y': int})
421 def identity(p: PointA) -> PointB:
422 return p
423 [builtins fixtures/dict.pyi]
424 [typing fixtures/typing-typeddict.pyi]
425
426 [case testCannotConvertTypedDictToSimilarTypedDictWithNarrowerItemTypes]
427 from typing import TypedDict
428 Point = TypedDict('Point', {'x': int, 'y': int})
429 ObjectPoint = TypedDict('ObjectPoint', {'x': object, 'y': object})
430 def convert(op: ObjectPoint) -> Point:
431 return op # E: Incompatible return value type (got "ObjectPoint", expected "Point")
432 [builtins fixtures/dict.pyi]
433 [typing fixtures/typing-typeddict.pyi]
434
435 [case testCannotConvertTypedDictToSimilarTypedDictWithWiderItemTypes]
436 from typing import TypedDict
437 Point = TypedDict('Point', {'x': int, 'y': int})
438 ObjectPoint = TypedDict('ObjectPoint', {'x': object, 'y': object})
439 def convert(p: Point) -> ObjectPoint:
440 return p # E: Incompatible return value type (got "Point", expected "ObjectPoint")
441 [builtins fixtures/dict.pyi]
442 [typing fixtures/typing-typeddict.pyi]
443
444 [case testCannotConvertTypedDictToSimilarTypedDictWithIncompatibleItemTypes]
445 from typing import TypedDict
446 Point = TypedDict('Point', {'x': int, 'y': int})
447 Chameleon = TypedDict('Chameleon', {'x': str, 'y': str})
448 def convert(p: Point) -> Chameleon:
449 return p # E: Incompatible return value type (got "Point", expected "Chameleon")
450 [builtins fixtures/dict.pyi]
451 [typing fixtures/typing-typeddict.pyi]
452
453 [case testCanConvertTypedDictToNarrowerTypedDict]
454 from typing import TypedDict
455 Point = TypedDict('Point', {'x': int, 'y': int})
456 Point1D = TypedDict('Point1D', {'x': int})
457 def narrow(p: Point) -> Point1D:
458 return p
459 [builtins fixtures/dict.pyi]
460 [typing fixtures/typing-typeddict.pyi]
461
462 [case testCannotConvertTypedDictToWiderTypedDict]
463 from typing import TypedDict
464 Point = TypedDict('Point', {'x': int, 'y': int})
465 Point3D = TypedDict('Point3D', {'x': int, 'y': int, 'z': int})
466 def widen(p: Point) -> Point3D:
467 return p # E: Incompatible return value type (got "Point", expected "Point3D")
468 [builtins fixtures/dict.pyi]
469 [typing fixtures/typing-typeddict.pyi]
470
471 [case testCanConvertTypedDictToCompatibleMapping]
472 from typing import Mapping, TypedDict
473 Point = TypedDict('Point', {'x': int, 'y': int})
474 def as_mapping(p: Point) -> Mapping[str, object]:
475 return p
476 [builtins fixtures/dict.pyi]
477 [typing fixtures/typing-typeddict.pyi]
478
479 [case testCannotConvertTypedDictToIncompatibleMapping]
480 from typing import Mapping, TypedDict
481 Point = TypedDict('Point', {'x': int, 'y': int})
482 def as_mapping(p: Point) -> Mapping[str, int]:
483 return p # E: Incompatible return value type (got "Point", expected "Mapping[str, int]")
484 [builtins fixtures/dict.pyi]
485 [typing fixtures/typing-typeddict.pyi]
486
487 [case testTypedDictAcceptsIntForFloatDuckTypes]
488 from typing import Any, Mapping, TypedDict
489 Point = TypedDict('Point', {'x': float, 'y': float})
490 def create_point() -> Point:
491 return Point(x=1, y=2)
492 reveal_type(Point(x=1, y=2)) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.float, 'y': builtins.float})"
493 [builtins fixtures/dict.pyi]
494 [typing fixtures/typing-typeddict.pyi]
495
496 [case testTypedDictDoesNotAcceptsFloatForInt]
497 from typing import Any, Mapping, TypedDict
498 Point = TypedDict('Point', {'x': int, 'y': int})
499 def create_point() -> Point:
500 return Point(x=1.2, y=2.5)
501 [out]
502 main:4: error: Incompatible types (expression has type "float", TypedDict item "x" has type "int")
503 main:4: error: Incompatible types (expression has type "float", TypedDict item "y" has type "int")
504 [builtins fixtures/dict.pyi]
505 [typing fixtures/typing-typeddict.pyi]
506
507 [case testTypedDictAcceptsAnyType]
508 from typing import Any, Mapping, TypedDict
509 Point = TypedDict('Point', {'x': float, 'y': float})
510 def create_point(something: Any) -> Point:
511 return Point({
512 'x': something.x,
513 'y': something.y
514 })
515 [builtins fixtures/dict.pyi]
516 [typing fixtures/typing-typeddict.pyi]
517
518 [case testTypedDictValueTypeContext]
519 from typing import List, TypedDict
520 D = TypedDict('D', {'x': List[int]})
521 reveal_type(D(x=[])) # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.list[builtins.int]})"
522 [builtins fixtures/dict.pyi]
523 [typing fixtures/typing-typeddict.pyi]
524
525 [case testCannotConvertTypedDictToDictOrMutableMapping]
526 from typing import Dict, MutableMapping, TypedDict
527 Point = TypedDict('Point', {'x': int, 'y': int})
528 def as_dict(p: Point) -> Dict[str, int]:
529 return p # E: Incompatible return value type (got "Point", expected "dict[str, int]")
530 def as_mutable_mapping(p: Point) -> MutableMapping[str, object]:
531 return p # E: Incompatible return value type (got "Point", expected "MutableMapping[str, object]")
532 [builtins fixtures/dict.pyi]
533 [typing fixtures/typing-full.pyi]
534
535 [case testCanConvertTypedDictToAny]
536 from typing import Any, TypedDict
537 Point = TypedDict('Point', {'x': int, 'y': int})
538 def unprotect(p: Point) -> Any:
539 return p
540 [builtins fixtures/dict.pyi]
541 [typing fixtures/typing-typeddict.pyi]
542
543 [case testAnonymousTypedDictInErrorMessages]
544 from typing import TypedDict
545
546 A = TypedDict('A', {'x': int, 'y': str})
547 B = TypedDict('B', {'x': int, 'z': str, 'a': int})
548 C = TypedDict('C', {'x': int, 'z': str, 'a': str})
549 a: A
550 b: B
551 c: C
552
553 def f(a: A) -> None: pass
554
555 l = [a, b] # Join generates an anonymous TypedDict
556 f(l) # E: Argument 1 to "f" has incompatible type "list[TypedDict({'x': int})]"; expected "A"
557 ll = [b, c]
558 f(ll) # E: Argument 1 to "f" has incompatible type "list[TypedDict({'x': int, 'z': str, 'a'=: object})]"; expected "A"
559 [builtins fixtures/dict.pyi]
560 [typing fixtures/typing-typeddict.pyi]
561
562 [case testTypedDictWithSimpleProtocol]
563 from typing import Protocol, TypedDict
564
565 class StrObjectMap(Protocol):
566 def __getitem__(self, key: str) -> object: ...
567 class StrIntMap(Protocol):
568 def __getitem__(self, key: str) -> int: ...
569
570 A = TypedDict('A', {'x': int, 'y': int})
571 B = TypedDict('B', {'x': int, 'y': str})
572
573 def fun(arg: StrObjectMap) -> None: ...
574 def fun2(arg: StrIntMap) -> None: ...
575 a: A
576 b: B
577 fun(a)
578 fun(b)
579 fun2(a) # Error
580 [builtins fixtures/dict.pyi]
581 [typing fixtures/typing-typeddict.pyi]
582 [out]
583 main:17: error: Argument 1 to "fun2" has incompatible type "A"; expected "StrIntMap"
584 main:17: note: Following member(s) of "A" have conflicts:
585 main:17: note: Expected:
586 main:17: note: def __getitem__(self, str, /) -> int
587 main:17: note: Got:
588 main:17: note: def __getitem__(self, str, /) -> object
589
590 [case testTypedDictWithSimpleProtocolInference]
591 from typing import Protocol, TypedDict, TypeVar
592
593 T_co = TypeVar('T_co', covariant=True)
594 T = TypeVar('T')
595
596 class StrMap(Protocol[T_co]):
597 def __getitem__(self, key: str) -> T_co: ...
598
599 A = TypedDict('A', {'x': int, 'y': int})
600 B = TypedDict('B', {'x': int, 'y': str})
601
602 def fun(arg: StrMap[T]) -> T:
603 return arg['whatever']
604 a: A
605 b: B
606 reveal_type(fun(a)) # N: Revealed type is "builtins.object"
607 reveal_type(fun(b)) # N: Revealed type is "builtins.object"
608 [builtins fixtures/dict.pyi]
609 [typing fixtures/typing-typeddict.pyi]
610
611 -- Join
612
613 [case testJoinOfTypedDictHasOnlyCommonKeysAndNewFallback]
614 from typing import TypedDict
615 TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
616 Point3D = TypedDict('Point3D', {'x': int, 'y': int, 'z': int})
617 p1 = TaggedPoint(type='2d', x=0, y=0)
618 p2 = Point3D(x=1, y=1, z=1)
619 joined_points = [p1, p2][0]
620 reveal_type(p1.values()) # N: Revealed type is "typing.Iterable[builtins.object]"
621 reveal_type(p2.values()) # N: Revealed type is "typing.Iterable[builtins.object]"
622 reveal_type(joined_points) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.int})"
623 [builtins fixtures/dict.pyi]
624 [typing fixtures/typing-typeddict.pyi]
625
626 [case testJoinOfTypedDictJoinsNonequivalentKeys]
627 from typing import TypedDict, NotRequired
628 CellWithInt = TypedDict('CellWithInt', {'value': object, 'meta': int})
629 CellWithString = TypedDict('CellWithString', {'value': object, 'meta': str})
630 CellWithNonRequiredInt = TypedDict('CellWithNonRequiredInt', {'value': object, 'meta': NotRequired[int]})
631 CellWithNonRequiredString = TypedDict('CellWithNonRequiredString', {'value': object, 'meta': NotRequired[str]})
632 c1 = CellWithInt(value=1, meta=42)
633 c2 = CellWithString(value=2, meta='turtle doves')
634 c3 = CellWithNonRequiredInt(value=1)
635 c4 = CellWithNonRequiredString(value=2)
636 j12 = [c1, c2]
637 j14 = [c1, c4]
638 j32 = [c3, c2]
639 j34 = [c3, c4]
640 reveal_type(c1) # N: Revealed type is "TypedDict('__main__.CellWithInt', {'value': builtins.object, 'meta': builtins.int})"
641 reveal_type(c2) # N: Revealed type is "TypedDict('__main__.CellWithString', {'value': builtins.object, 'meta': builtins.str})"
642 reveal_type(c3) # N: Revealed type is "TypedDict('__main__.CellWithNonRequiredInt', {'value': builtins.object, 'meta'?: builtins.int})"
643 reveal_type(c4) # N: Revealed type is "TypedDict('__main__.CellWithNonRequiredString', {'value': builtins.object, 'meta'?: builtins.str})"
644 reveal_type(j12) # N: Revealed type is "builtins.list[TypedDict({'value': builtins.object, 'meta'=: builtins.object})]"
645 reveal_type(j14) # N: Revealed type is "builtins.list[TypedDict({'value': builtins.object, 'meta'?=: builtins.object})]"
646 reveal_type(j32) # N: Revealed type is "builtins.list[TypedDict({'value': builtins.object, 'meta'?=: builtins.object})]"
647 reveal_type(j34) # N: Revealed type is "builtins.list[TypedDict({'value': builtins.object, 'meta'?=: builtins.object})]"
648 [builtins fixtures/dict.pyi]
649 [typing fixtures/typing-typeddict.pyi]
650
651 [case testJoinOfDisjointTypedDictsIsEmptyTypedDict]
652 from typing import TypedDict
653 Point = TypedDict('Point', {'x': int, 'y': int})
654 Cell = TypedDict('Cell', {'value': object})
655 d1 = Point(x=0, y=0)
656 d2 = Cell(value='pear tree')
657 joined_dicts = [d1, d2]
658 reveal_type(d1) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})"
659 reveal_type(d2) # N: Revealed type is "TypedDict('__main__.Cell', {'value': builtins.object})"
660 reveal_type(joined_dicts) # N: Revealed type is "builtins.list[TypedDict({})]"
661 [builtins fixtures/dict.pyi]
662 [typing fixtures/typing-typeddict.pyi]
663
664 [case testJoinOfTypedDictWithCompatibleMappingIsMapping]
665 from typing import Mapping, TypedDict
666 Cell = TypedDict('Cell', {'value': int})
667 left = Cell(value=42)
668 right = {'score': 999} # type: Mapping[str, int]
669 joined1 = [left, right]
670 joined2 = [right, left]
671 reveal_type(joined1) # N: Revealed type is "builtins.list[typing.Mapping[builtins.str, builtins.object]]"
672 reveal_type(joined2) # N: Revealed type is "builtins.list[typing.Mapping[builtins.str, builtins.object]]"
673 [builtins fixtures/dict.pyi]
674 [typing fixtures/typing-typeddict.pyi]
675
676 [case testJoinOfTypedDictWithCompatibleMappingSupertypeIsSupertype]
677 from typing import Sized, TypedDict
678 Cell = TypedDict('Cell', {'value': int})
679 left = Cell(value=42)
680 right = {'score': 999} # type: Sized
681 joined1 = [left, right]
682 joined2 = [right, left]
683 reveal_type(joined1) # N: Revealed type is "builtins.list[typing.Sized]"
684 reveal_type(joined2) # N: Revealed type is "builtins.list[typing.Sized]"
685 [builtins fixtures/dict.pyi]
686 [typing fixtures/typing-typeddict.pyi]
687
688 [case testJoinOfTypedDictWithIncompatibleTypeIsObject]
689 from typing import Mapping, TypedDict
690 Cell = TypedDict('Cell', {'value': int})
691 left = Cell(value=42)
692 right = 42
693 joined1 = [left, right]
694 joined2 = [right, left]
695 reveal_type(joined1) # N: Revealed type is "builtins.list[builtins.object]"
696 reveal_type(joined2) # N: Revealed type is "builtins.list[builtins.object]"
697 [builtins fixtures/dict.pyi]
698 [typing fixtures/typing-typeddict.pyi]
699
700
701 -- Meet
702
703 [case testMeetOfTypedDictsWithCompatibleCommonKeysHasAllKeysAndNewFallback]
704 from typing import TypedDict, TypeVar, Callable
705 XY = TypedDict('XY', {'x': int, 'y': int})
706 YZ = TypedDict('YZ', {'y': int, 'z': int})
707 T = TypeVar('T')
708 def f(x: Callable[[T, T], None]) -> T: pass
709 def g(x: XY, y: YZ) -> None: pass
710 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.int, 'z': builtins.int})"
711 [builtins fixtures/dict.pyi]
712 [typing fixtures/typing-typeddict.pyi]
713
714 [case testMeetOfTypedDictsWithAny]
715 from typing import Any, TypedDict, TypeVar, Callable
716 A = TypedDict('A', {'x': Any})
717 B = TypedDict('B', {'x': int})
718 T = TypeVar('T')
719 def f(x: Callable[[T, T], None]) -> T: pass
720 def gAB(x: A, y: B) -> None: pass
721 def gBA(x: B, y: A) -> None: pass
722 reveal_type(f(gAB)) # N: Revealed type is "TypedDict({'x': builtins.int})"
723 reveal_type(f(gBA)) # N: Revealed type is "TypedDict({'x': builtins.int})"
724 [builtins fixtures/dict.pyi]
725 [typing fixtures/typing-typeddict.pyi]
726
727 [case testMeetOfTypedDictMissingAndAny]
728 from typing import Any, TypedDict, TypeVar, Callable, ReadOnly
729 T = TypeVar('T')
730 def meet(x: Callable[[T, T], None]) -> T: pass
731 A = TypedDict('A', {'x': Any})
732 B = TypedDict('B', {'y': Any})
733 C = TypedDict('C', {'y': Any}, total=False)
734 def fAB(x: A, y: B) -> None: pass
735 def fBA(x: B, y: A) -> None: pass
736 def fAC(x: A, y: C) -> None: pass
737 def fCA(x: C, y: A) -> None: pass
738 if int():
739 reveal_type(meet(fAB)) # N: Revealed type is "TypedDict({'x': Any, 'y': Any})"
740 if int():
741 reveal_type(meet(fBA)) # N: Revealed type is "TypedDict({'y': Any, 'x': Any})"
742 if int():
743 reveal_type(meet(fAC)) # N: Revealed type is "TypedDict({'x': Any, 'y'?: Any})"
744 if int():
745 reveal_type(meet(fCA)) # N: Revealed type is "TypedDict({'y'?: Any, 'x': Any})"
746 [builtins fixtures/dict.pyi]
747 [typing fixtures/typing-typeddict.pyi]
748
749 [case testMeetOfTypedDictsNotRequiredNeverAndAny]
750 from typing import Any, NotRequired, TypedDict, TypeVar, Callable
751 from typing_extensions import Never
752 A = TypedDict('A', {'x': NotRequired[Any], 'y': NotRequired[Never]})
753 B = TypedDict('B', {'x': NotRequired[Never], 'y': NotRequired[Any]})
754 T = TypeVar('T')
755 def f(x: Callable[[T, T], None]) -> T: pass
756 def g(x: A, y: B) -> None: pass
757 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'?: Never, 'y'?: Never})"
758 [builtins fixtures/dict.pyi]
759 [typing fixtures/typing-typeddict.pyi]
760
761 [case testMeetOfTypedDictsWithIncompatibleCommonKeysIsUninhabited]
762 from typing import TypedDict, TypeVar, Callable
763 XYa = TypedDict('XYa', {'x': int, 'y': int})
764 YbZ = TypedDict('YbZ', {'y': object, 'z': int})
765 T = TypeVar('T')
766 def f(x: Callable[[T, T], None]) -> T: pass
767 def g(x: XYa, y: YbZ) -> None: pass
768 reveal_type(f(g)) # N: Revealed type is "Never"
769 [builtins fixtures/dict.pyi]
770 [typing fixtures/typing-typeddict.pyi]
771
772 [case testMeetOfTypedDictsWithNoCommonKeysHasAllKeysAndNewFallback]
773 from typing import TypedDict, TypeVar, Callable
774 X = TypedDict('X', {'x': int})
775 Z = TypedDict('Z', {'z': int})
776 T = TypeVar('T')
777 def f(x: Callable[[T, T], None]) -> T: pass
778 def g(x: X, y: Z) -> None: pass
779 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x': builtins.int, 'z': builtins.int})"
780 [builtins fixtures/dict.pyi]
781 [typing fixtures/typing-typeddict.pyi]
782
783 # TODO: It would be more accurate for the meet to be TypedDict instead.
784 [case testMeetOfTypedDictWithCompatibleMappingIsUninhabitedForNow]
785 from typing import TypedDict, TypeVar, Callable, Mapping
786 X = TypedDict('X', {'x': int})
787 M = Mapping[str, int]
788 T = TypeVar('T')
789 def f(x: Callable[[T, T], None]) -> T: pass
790 def g(x: X, y: M) -> None: pass
791 reveal_type(f(g)) # N: Revealed type is "Never"
792 [builtins fixtures/dict.pyi]
793 [typing fixtures/typing-typeddict.pyi]
794
795 [case testMeetOfTypedDictWithIncompatibleMappingIsUninhabited]
796 from typing import TypedDict, TypeVar, Callable, Mapping
797 X = TypedDict('X', {'x': int})
798 M = Mapping[str, str]
799 T = TypeVar('T')
800 def f(x: Callable[[T, T], None]) -> T: pass
801 def g(x: X, y: M) -> None: pass
802 reveal_type(f(g)) # N: Revealed type is "Never"
803 [builtins fixtures/dict.pyi]
804 [typing fixtures/typing-typeddict.pyi]
805
806 [case testMeetOfTypedDictWithCompatibleMappingSuperclassIsUninhabitedForNow]
807 from typing import TypedDict, TypeVar, Callable, Iterable
808 X = TypedDict('X', {'x': int})
809 I = Iterable[str]
810 T = TypeVar('T')
811 def f(x: Callable[[T, T], None]) -> T: pass
812 def g(x: X, y: I) -> None: pass
813 reveal_type(f(g)) # N: Revealed type is "TypedDict('__main__.X', {'x': builtins.int})"
814 [builtins fixtures/dict.pyi]
815 [typing fixtures/typing-typeddict.pyi]
816
817 [case testMeetOfTypedDictsWithNonTotal]
818 from typing import TypedDict, TypeVar, Callable
819 XY = TypedDict('XY', {'x': int, 'y': int}, total=False)
820 YZ = TypedDict('YZ', {'y': int, 'z': int}, total=False)
821 T = TypeVar('T')
822 def f(x: Callable[[T, T], None]) -> T: pass
823 def g(x: XY, y: YZ) -> None: pass
824 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'?: builtins.int, 'y'?: builtins.int, 'z'?: builtins.int})"
825 [builtins fixtures/dict.pyi]
826 [typing fixtures/typing-typeddict.pyi]
827
828 [case testMeetOfTypedDictsWithNonTotalAndTotal]
829 from typing import TypedDict, TypeVar, Callable
830 XY = TypedDict('XY', {'x': int}, total=False)
831 YZ = TypedDict('YZ', {'y': int, 'z': int})
832 T = TypeVar('T')
833 def f(x: Callable[[T, T], None]) -> T: pass
834 def g(x: XY, y: YZ) -> None: pass
835 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'?: builtins.int, 'y': builtins.int, 'z': builtins.int})"
836 [builtins fixtures/dict.pyi]
837 [typing fixtures/typing-typeddict.pyi]
838
839 [case testMeetOfTypedDictsWithIncompatibleNonTotalAndTotal]
840 from typing import TypedDict, TypeVar, Callable
841 XY = TypedDict('XY', {'x': int, 'y': int}, total=False)
842 YZ = TypedDict('YZ', {'y': int, 'z': int})
843 T = TypeVar('T')
844 def f(x: Callable[[T, T], None]) -> T: pass
845 def g(x: XY, y: YZ) -> None: pass
846 reveal_type(f(g)) # N: Revealed type is "Never"
847 [builtins fixtures/dict.pyi]
848 [typing fixtures/typing-typeddict.pyi]
849
850
851 -- Constraint Solver
852
853 [case testTypedDictConstraintsAgainstIterable]
854 from typing import TypedDict, TypeVar, Iterable
855 T = TypeVar('T')
856 def f(x: Iterable[T]) -> T: pass
857 A = TypedDict('A', {'x': int})
858 a: A
859 reveal_type(f(a)) # N: Revealed type is "builtins.str"
860 [builtins fixtures/dict.pyi]
861 [typing fixtures/typing-typeddict.pyi]
862
863 -- TODO: Figure out some way to trigger the ConstraintBuilderVisitor.visit_typeddict_type() path.
864
865
866 -- Special Method: __getitem__
867
868 [case testCanGetItemOfTypedDictWithValidStringLiteralKey]
869 from typing import TypedDict
870 TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
871 p = TaggedPoint(type='2d', x=42, y=1337)
872 reveal_type(p['type']) # N: Revealed type is "builtins.str"
873 reveal_type(p['x']) # N: Revealed type is "builtins.int"
874 reveal_type(p['y']) # N: Revealed type is "builtins.int"
875 [builtins fixtures/dict.pyi]
876 [typing fixtures/typing-typeddict.pyi]
877
878 [case testCannotGetItemOfTypedDictWithInvalidStringLiteralKey]
879 from typing import TypedDict
880 TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
881 p: TaggedPoint
882 p['typ'] # E: TypedDict "TaggedPoint" has no key "typ" \
883 # N: Did you mean "type"?
884 [builtins fixtures/dict.pyi]
885 [typing fixtures/typing-typeddict.pyi]
886
887 [case testCannotGetItemOfAnonymousTypedDictWithInvalidStringLiteralKey]
888 from typing import TypedDict, TypeVar
889 A = TypedDict('A', {'x': str, 'y': int, 'z': str})
890 B = TypedDict('B', {'x': str, 'z': int})
891 C = TypedDict('C', {'x': str, 'y': int, 'z': int})
892 T = TypeVar('T')
893 def join(x: T, y: T) -> T: return x
894 ab = join(A(x='', y=1, z=''), B(x='', z=1))
895 ac = join(A(x='', y=1, z=''), C(x='', y=0, z=1))
896 ab['y'] # E: "y" is not a valid TypedDict key; expected one of ("x", "z")
897 ac['a'] # E: "a" is not a valid TypedDict key; expected one of ("x", "y", "z")
898 [builtins fixtures/dict.pyi]
899 [typing fixtures/typing-typeddict.pyi]
900
901 [case testCannotGetItemOfTypedDictWithNonLiteralKey]
902 from typing import TypedDict, Union
903 TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
904 p = TaggedPoint(type='2d', x=42, y=1337)
905 def get_coordinate(p: TaggedPoint, key: str) -> Union[str, int]:
906 return p[key] # E: TypedDict key must be a string literal; expected one of ("type", "x", "y")
907 [builtins fixtures/dict.pyi]
908 [typing fixtures/typing-typeddict.pyi]
909
910 [case testCanGetItemOfTypedDictWithStringLiteralKeyInComprehension]
911 from typing import TypedDict
912 Data = TypedDict('Data', {'field1': int, 'field2': str, 'field3': str})
913 data: Data
914 def is_str(value: object) -> bool: ...
915 filtered_keys1 = [data[key] for key in ("field1", "field2", "field3")]
916 filtered_keys2 = [key for key in ("field1", "field2", "field3") if is_str(data[key])]
917 reveal_type(filtered_keys1) # N: Revealed type is "builtins.list[builtins.int | builtins.str]"
918 reveal_type(filtered_keys2) # N: Revealed type is "builtins.list[builtins.str]"
919 [builtins fixtures/for.pyi]
920 [typing fixtures/typing-full.pyi]
921
922 -- Special Method: __setitem__
923
924 [case testCanSetItemOfTypedDictWithValidStringLiteralKeyAndCompatibleValueType]
925 from typing import TypedDict
926 TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
927 p = TaggedPoint(type='2d', x=42, y=1337)
928 p['type'] = 'two_d'
929 p['x'] = 1
930 [builtins fixtures/dict.pyi]
931 [typing fixtures/typing-typeddict.pyi]
932
933 [case testCannotSetItemOfTypedDictWithIncompatibleValueType]
934 from typing import TypedDict
935 TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
936 p = TaggedPoint(type='2d', x=42, y=1337)
937 p['x'] = 'y' # E: Value of "x" has incompatible type "str"; expected "int"
938 [builtins fixtures/dict.pyi]
939 [typing fixtures/typing-typeddict.pyi]
940
941 [case testCannotSetItemOfTypedDictWithInvalidStringLiteralKey]
942 from typing import TypedDict
943 TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
944 p = TaggedPoint(type='2d', x=42, y=1337)
945 p['z'] = 1 # E: TypedDict "TaggedPoint" has no key "z"
946 [builtins fixtures/dict.pyi]
947 [typing fixtures/typing-typeddict.pyi]
948
949 [case testCannotSetItemOfTypedDictWithNonLiteralKey]
950 from typing import TypedDict, Union
951 TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
952 p = TaggedPoint(type='2d', x=42, y=1337)
953 def set_coordinate(p: TaggedPoint, key: str, value: int) -> None:
954 p[key] = value # E: TypedDict key must be a string literal; expected one of ("type", "x", "y")
955 [builtins fixtures/dict.pyi]
956 [typing fixtures/typing-typeddict.pyi]
957
958
959 -- isinstance
960
961 [case testTypedDictWithIsInstanceAndIsSubclass]
962 from typing import TypedDict
963 D = TypedDict('D', {'x': int})
964 d: object
965 if isinstance(d, D): # E: Cannot use isinstance() with TypedDict type
966 reveal_type(d) # N: Revealed type is "__main__.D"
967 issubclass(object, D) # E: Cannot use issubclass() with TypedDict type
968 [builtins fixtures/isinstancelist.pyi]
969 [typing fixtures/typing-typeddict.pyi]
970
971
972 -- Scoping
973
974 [case testTypedDictInClassNamespace]
975 # https://github.com/python/mypy/pull/2553#issuecomment-266474341
976 from typing import TypedDict
977 class C:
978 def f(self):
979 A = TypedDict('A', {'x': int})
980 def g(self):
981 A = TypedDict('A', {'y': int})
982 C.A # E: "type[C]" has no attribute "A"
983 [builtins fixtures/dict.pyi]
984 [typing fixtures/typing-typeddict.pyi]
985
986 [case testTypedDictInFunction]
987 from typing import TypedDict
988 def f() -> None:
989 A = TypedDict('A', {'x': int})
990 A # E: Name "A" is not defined
991 [builtins fixtures/dict.pyi]
992 [typing fixtures/typing-typeddict.pyi]
993
994
995 -- Union simplification / proper subtype checks
996
997 [case testTypedDictUnionSimplification]
998 from typing import TypedDict, TypeVar, Union, Any, cast
999
1000 T = TypeVar('T')
1001 S = TypeVar('S')
1002 def u(x: T, y: S) -> Union[S, T]: pass
1003
1004 C = TypedDict('C', {'a': int})
1005 D = TypedDict('D', {'a': int, 'b': int})
1006 E = TypedDict('E', {'a': str})
1007 F = TypedDict('F', {'x': int})
1008 G = TypedDict('G', {'a': Any})
1009
1010 c = C(a=1)
1011 d = D(a=1, b=1)
1012 e = E(a='')
1013 f = F(x=1)
1014 g = G(a=cast(Any, 1)) # Work around #2610
1015
1016 reveal_type(u(d, d)) # N: Revealed type is "TypedDict('__main__.D', {'a': builtins.int, 'b': builtins.int})"
1017 reveal_type(u(c, d)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int})"
1018 reveal_type(u(d, c)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int})"
1019 reveal_type(u(c, e)) # N: Revealed type is "TypedDict('__main__.E', {'a': builtins.str}) | TypedDict('__main__.C', {'a': builtins.int})"
1020 reveal_type(u(e, c)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int}) | TypedDict('__main__.E', {'a': builtins.str})"
1021 reveal_type(u(c, f)) # N: Revealed type is "TypedDict('__main__.F', {'x': builtins.int}) | TypedDict('__main__.C', {'a': builtins.int})"
1022 reveal_type(u(f, c)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int}) | TypedDict('__main__.F', {'x': builtins.int})"
1023 reveal_type(u(c, g)) # N: Revealed type is "TypedDict('__main__.G', {'a': Any}) | TypedDict('__main__.C', {'a': builtins.int})"
1024 reveal_type(u(g, c)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int}) | TypedDict('__main__.G', {'a': Any})"
1025 [builtins fixtures/dict.pyi]
1026 [typing fixtures/typing-typeddict.pyi]
1027
1028 [case testTypedDictUnionSimplification2]
1029 from typing import TypedDict, TypeVar, Union, Mapping, Any
1030
1031 T = TypeVar('T')
1032 S = TypeVar('S')
1033 def u(x: T, y: S) -> Union[S, T]: pass
1034
1035 C = TypedDict('C', {'a': int, 'b': int})
1036
1037 c = C(a=1, b=1)
1038 m_s_o: Mapping[str, object]
1039 m_s_s: Mapping[str, str]
1040 m_i_i: Mapping[int, int]
1041 m_s_a: Mapping[str, Any]
1042
1043 reveal_type(u(c, m_s_o)) # N: Revealed type is "typing.Mapping[builtins.str, builtins.object]"
1044 reveal_type(u(m_s_o, c)) # N: Revealed type is "typing.Mapping[builtins.str, builtins.object]"
1045 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})"
1046 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})"
1047 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})"
1048 [builtins fixtures/dict.pyi]
1049 [typing fixtures/typing-typeddict.pyi]
1050
1051 [case testTypedDictUnionUnambiguousCase]
1052 from typing import Union, Literal, Mapping, TypedDict, Any, cast
1053
1054 A = TypedDict('A', {'@type': Literal['a-type'], 'a': str})
1055 B = TypedDict('B', {'@type': Literal['b-type'], 'b': int})
1056
1057 c: Union[A, B] = {'@type': 'a-type', 'a': 'Test'}
1058 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})"
1059 [builtins fixtures/dict.pyi]
1060 [typing fixtures/typing-typeddict.pyi]
1061
1062 [case testTypedDictUnionAmbiguousCaseBothMatch]
1063 from typing import Union, Literal, Mapping, TypedDict, Any, cast
1064
1065 A = TypedDict('A', {'@type': Literal['a-type'], 'value': str})
1066 B = TypedDict('B', {'@type': Literal['b-type'], 'value': str})
1067
1068 c: Union[A, B] = {'@type': 'a-type', 'value': 'Test'}
1069 [builtins fixtures/dict.pyi]
1070 [typing fixtures/typing-typeddict.pyi]
1071
1072 [case testTypedDictUnionAmbiguousCaseNoMatch]
1073 from typing import Union, Literal, Mapping, TypedDict, Any, cast
1074
1075 A = TypedDict('A', {'@type': Literal['a-type'], 'value': int})
1076 B = TypedDict('B', {'@type': Literal['b-type'], 'value': int})
1077
1078 c: Union[A, B] = {'@type': 'a-type', 'value': 'Test'} # E: Type of TypedDict is ambiguous, none of ("A", "B") matches cleanly \
1079 # E: Incompatible types in assignment (expression has type "dict[str, str]", variable has type "A | B")
1080 [builtins fixtures/dict.pyi]
1081 [typing fixtures/typing-typeddict.pyi]
1082
1083 [case testTypedDictUnionWithNonTypedDictLiteralKey]
1084 from typing import Union, TypedDict
1085
1086 class Foo(TypedDict):
1087 some: str
1088 name: str
1089
1090 baz: Union[Foo, dict[int, float]] = {1: 5.2}
1091 baz2: Union[Foo, dict[int, float]] = {'some': 'x', 'name': 'y'}
1092 [builtins fixtures/dict.pyi]
1093 [typing fixtures/typing-typeddict.pyi]
1094
1095 -- Use dict literals
1096
1097 [case testTypedDictDictLiterals]
1098 from typing import TypedDict
1099
1100 Point = TypedDict('Point', {'x': int, 'y': int})
1101
1102 def f(p: Point) -> None:
1103 if int():
1104 p = {'x': 2, 'y': 3}
1105 p = {'x': 2} # E: Missing key "y" for TypedDict "Point"
1106 p = dict(x=2, y=3)
1107
1108 f({'x': 1, 'y': 3})
1109 f({'x': 1, 'y': 'z'}) # E: Incompatible types (expression has type "str", TypedDict item "y" has type "int")
1110
1111 f(dict(x=1, y=3))
1112 f(dict(x=1, y=3, z=4)) # E: Extra key "z" for TypedDict "Point"
1113 f(dict(x=1, y=3, z=4, a=5)) # E: Extra keys ("z", "a") for TypedDict "Point"
1114
1115 [builtins fixtures/dict.pyi]
1116 [typing fixtures/typing-typeddict.pyi]
1117
1118 [case testTypedDictExplicitTypes]
1119 from typing import TypedDict
1120
1121 Point = TypedDict('Point', {'x': int, 'y': int})
1122
1123 p1a: Point = {'x': 'hi'} # E: Missing key "y" for TypedDict "Point"
1124 p1b: Point = {} # E: Missing keys ("x", "y") for TypedDict "Point"
1125
1126 p2: Point
1127 p2 = dict(x='bye') # E: Missing key "y" for TypedDict "Point"
1128
1129 p3 = Point(x=1, y=2)
1130 if int():
1131 p3 = {'x': 'hi'} # E: Missing key "y" for TypedDict "Point"
1132
1133 p4: Point = {'x': 1, 'y': 2}
1134
1135 [builtins fixtures/dict.pyi]
1136 [typing fixtures/typing-typeddict.pyi]
1137
1138 [case testCannotCreateAnonymousTypedDictInstanceUsingDictLiteralWithExtraItems]
1139 from typing import TypedDict, TypeVar
1140 A = TypedDict('A', {'x': int, 'y': int})
1141 B = TypedDict('B', {'x': int})
1142 T = TypeVar('T')
1143 def join(x: T, y: T) -> T: return x
1144 ab = join(A(x=1, y=1), B(x=1))
1145 if int():
1146 ab = {'x': 1, 'z': 1} # E: Expected TypedDict key "x" but found keys ("x", "z")
1147 [builtins fixtures/dict.pyi]
1148 [typing fixtures/typing-typeddict.pyi]
1149
1150 [case testCannotCreateAnonymousTypedDictInstanceUsingDictLiteralWithMissingItems]
1151 from typing import TypedDict, TypeVar
1152 A = TypedDict('A', {'x': int, 'y': int, 'z': int})
1153 B = TypedDict('B', {'x': int, 'y': int, 'z': str})
1154 T = TypeVar('T')
1155 def join(x: T, y: T) -> T: return x
1156 ab = join(A(x=1, y=1, z=1), B(x=1, y=1, z=''))
1157 if int():
1158 ab = {} # E: Expected TypedDict keys ("x", "y", "z") but found no keys
1159 [builtins fixtures/dict.pyi]
1160 [typing fixtures/typing-typeddict.pyi]
1161
1162
1163 -- Other TypedDict methods
1164
1165
1166 [case testTypedDictGetMethodOverloads]
1167 from typing import TypedDict
1168 from typing_extensions import Required, NotRequired
1169
1170 class D(TypedDict):
1171 a: int
1172 b: NotRequired[str]
1173
1174 def test(d: D) -> None:
1175 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)"
1176 [builtins fixtures/dict.pyi]
1177 [typing fixtures/typing-typeddict.pyi]
1178
1179
1180 [case testTypedDictGetMethodTotalFalse]
1181 from typing import TypedDict, Literal
1182 class Unrelated: pass
1183 D = TypedDict('D', {'x': int, 'y': str}, total=False)
1184 d: D
1185 u: Unrelated
1186 x: Literal['x']
1187 y: Literal['y']
1188 z: Literal['z']
1189 x_or_y: Literal['x', 'y']
1190 x_or_z: Literal['x', 'z']
1191 x_or_y_or_z: Literal['x', 'y', 'z']
1192
1193 # test with literal expression
1194 reveal_type(d.get('x')) # N: Revealed type is "builtins.int | None"
1195 reveal_type(d.get('y')) # N: Revealed type is "builtins.str | None"
1196 reveal_type(d.get('z')) # N: Revealed type is "builtins.object"
1197 reveal_type(d.get('x', u)) # N: Revealed type is "builtins.int | __main__.Unrelated"
1198 reveal_type(d.get('x', 1)) # N: Revealed type is "builtins.int"
1199 reveal_type(d.get('y', None)) # N: Revealed type is "builtins.str | None"
1200
1201 # test with literal type / union of literal types with implicit default
1202 reveal_type(d.get(x)) # N: Revealed type is "builtins.int | None"
1203 reveal_type(d.get(y)) # N: Revealed type is "builtins.str | None"
1204 reveal_type(d.get(z)) # N: Revealed type is "builtins.object"
1205 reveal_type(d.get(x_or_y)) # N: Revealed type is "builtins.int | builtins.str | None"
1206 reveal_type(d.get(x_or_z)) # N: Revealed type is "builtins.object"
1207 reveal_type(d.get(x_or_y_or_z)) # N: Revealed type is "builtins.object"
1208
1209 # test with literal type / union of literal types with explicit default
1210 reveal_type(d.get(x, u)) # N: Revealed type is "builtins.int | __main__.Unrelated"
1211 reveal_type(d.get(y, u)) # N: Revealed type is "builtins.str | __main__.Unrelated"
1212 reveal_type(d.get(z, u)) # N: Revealed type is "builtins.object"
1213 reveal_type(d.get(x_or_y, u)) # N: Revealed type is "builtins.int | builtins.str | __main__.Unrelated"
1214 reveal_type(d.get(x_or_z, u)) # N: Revealed type is "builtins.object"
1215 reveal_type(d.get(x_or_y_or_z, u)) # N: Revealed type is "builtins.object"
1216 [builtins fixtures/dict.pyi]
1217 [typing fixtures/typing-typeddict.pyi]
1218
1219 [case testTypedDictGetMethodTotalTrue]
1220 from typing import TypedDict, Literal
1221 class Unrelated: pass
1222 D = TypedDict('D', {'x': int, 'y': str}, total=True)
1223 d: D
1224 u: Unrelated
1225 x: Literal['x']
1226 y: Literal['y']
1227 z: Literal['z']
1228 x_or_y: Literal['x', 'y']
1229 x_or_z: Literal['x', 'z']
1230 x_or_y_or_z: Literal['x', 'y', 'z']
1231
1232 # test with literal expression
1233 reveal_type(d.get('x')) # N: Revealed type is "builtins.int"
1234 reveal_type(d.get('y')) # N: Revealed type is "builtins.str"
1235 reveal_type(d.get('z')) # N: Revealed type is "builtins.object"
1236 reveal_type(d.get('x', u)) # N: Revealed type is "builtins.int"
1237 reveal_type(d.get('x', 1)) # N: Revealed type is "builtins.int"
1238 reveal_type(d.get('y', None)) # N: Revealed type is "builtins.str"
1239
1240 # test with literal type / union of literal types with implicit default
1241 reveal_type(d.get(x)) # N: Revealed type is "builtins.int"
1242 reveal_type(d.get(y)) # N: Revealed type is "builtins.str"
1243 reveal_type(d.get(z)) # N: Revealed type is "builtins.object"
1244 reveal_type(d.get(x_or_y)) # N: Revealed type is "builtins.int | builtins.str"
1245 reveal_type(d.get(x_or_z)) # N: Revealed type is "builtins.object"
1246 reveal_type(d.get(x_or_y_or_z)) # N: Revealed type is "builtins.object"
1247
1248 # test with literal type / union of literal types with explicit default
1249 reveal_type(d.get(x, u)) # N: Revealed type is "builtins.int"
1250 reveal_type(d.get(y, u)) # N: Revealed type is "builtins.str"
1251 reveal_type(d.get(z, u)) # N: Revealed type is "builtins.object"
1252 reveal_type(d.get(x_or_y, u)) # N: Revealed type is "builtins.int | builtins.str"
1253 reveal_type(d.get(x_or_z, u)) # N: Revealed type is "builtins.object"
1254 reveal_type(d.get(x_or_y_or_z, u)) # N: Revealed type is "builtins.object"
1255
1256 [builtins fixtures/dict.pyi]
1257 [typing fixtures/typing-typeddict.pyi]
1258
1259
1260 [case testTypedDictGetMethodTotalMixed]
1261 from typing import TypedDict, Literal
1262 from typing_extensions import Required, NotRequired
1263 class Unrelated: pass
1264 D = TypedDict('D', {'x': Required[int], 'y': NotRequired[str]})
1265 d: D
1266 u: Unrelated
1267 x: Literal['x']
1268 y: Literal['y']
1269 z: Literal['z']
1270 x_or_y: Literal['x', 'y']
1271 x_or_z: Literal['x', 'z']
1272 x_or_y_or_z: Literal['x', 'y', 'z']
1273
1274 # test with literal expression
1275 reveal_type(d.get('x')) # N: Revealed type is "builtins.int"
1276 reveal_type(d.get('y')) # N: Revealed type is "builtins.str | None"
1277 reveal_type(d.get('z')) # N: Revealed type is "builtins.object"
1278 reveal_type(d.get('x', u)) # N: Revealed type is "builtins.int"
1279 reveal_type(d.get('x', 1)) # N: Revealed type is "builtins.int"
1280 reveal_type(d.get('y', None)) # N: Revealed type is "builtins.str | None"
1281
1282 # test with literal type / union of literal types with implicit default
1283 reveal_type(d.get(x)) # N: Revealed type is "builtins.int"
1284 reveal_type(d.get(y)) # N: Revealed type is "builtins.str | None"
1285 reveal_type(d.get(z)) # N: Revealed type is "builtins.object"
1286 reveal_type(d.get(x_or_y)) # N: Revealed type is "builtins.int | builtins.str | None"
1287 reveal_type(d.get(x_or_z)) # N: Revealed type is "builtins.object"
1288 reveal_type(d.get(x_or_y_or_z)) # N: Revealed type is "builtins.object"
1289
1290 # test with literal type / union of literal types with explicit default
1291 reveal_type(d.get(x, u)) # N: Revealed type is "builtins.int"
1292 reveal_type(d.get(y, u)) # N: Revealed type is "builtins.str | __main__.Unrelated"
1293 reveal_type(d.get(z, u)) # N: Revealed type is "builtins.object"
1294 reveal_type(d.get(x_or_y, u)) # N: Revealed type is "builtins.int | builtins.str | __main__.Unrelated"
1295 reveal_type(d.get(x_or_z, u)) # N: Revealed type is "builtins.object"
1296 reveal_type(d.get(x_or_y_or_z, u)) # N: Revealed type is "builtins.object"
1297 [builtins fixtures/dict.pyi]
1298 [typing fixtures/typing-typeddict.pyi]
1299
1300
1301 [case testTypedDictGetMethodTypeContext]
1302 from typing import List, TypedDict
1303 class A: pass
1304 D = TypedDict('D', {'x': List[int], 'y': int}, total=False)
1305 d: D
1306 reveal_type(d.get('x', [])) # N: Revealed type is "builtins.list[builtins.int]"
1307 reveal_type(d.get('x', ['x'])) # N: Revealed type is "builtins.list[builtins.int] | builtins.list[builtins.str]"
1308 a = ['']
1309 reveal_type(d.get('x', a)) # N: Revealed type is "builtins.list[builtins.int] | builtins.list[builtins.str]"
1310 [builtins fixtures/dict.pyi]
1311 [typing fixtures/typing-typeddict.pyi]
1312
1313 [case testTypedDictGetMethodInvalidArgs]
1314 from typing import TypedDict
1315 D = TypedDict('D', {'x': int, 'y': str})
1316 d: D
1317 d.get() # E: All overload variants of "get" of "Mapping" require at least one argument \
1318 # N: Possible overload variants: \
1319 # N: def get(self, str, /) -> object \
1320 # N: def get(self, str, object, /) -> object \
1321 # N: def [V] get(self, str, V, /) -> object
1322 d.get('x', 1, 2) # E: No overload variant of "get" of "Mapping" matches argument types "str", "int", "int" \
1323 # N: Possible overload variants: \
1324 # N: def get(self, str, /) -> object \
1325 # N: def get(self, str, object, /) -> object \
1326 # N: def [V] get(self, str, int | V, /) -> object
1327 x = d.get('z')
1328 reveal_type(x) # N: Revealed type is "builtins.object"
1329 s = ''
1330 y = d.get(s)
1331 reveal_type(y) # N: Revealed type is "builtins.object"
1332 [builtins fixtures/dict.pyi]
1333 [typing fixtures/typing-typeddict.pyi]
1334
1335 [case testTypedDictMissingMethod]
1336 from typing import TypedDict
1337 D = TypedDict('D', {'x': int, 'y': str})
1338 d: D
1339 d.bad(1) # E: "D" has no attribute "bad"
1340 [builtins fixtures/dict.pyi]
1341 [typing fixtures/typing-typeddict.pyi]
1342
1343 [case testTypedDictChainedGetMethodWithDictFallback]
1344 from typing import TypedDict
1345 D = TypedDict('D', {'x': int, 'y': str})
1346 E = TypedDict('E', {'d': D})
1347 p = E(d=D(x=0, y=''))
1348 reveal_type(p.get('d', {'x': 1, 'y': ''})) # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.str})"
1349 [builtins fixtures/dict.pyi]
1350 [typing fixtures/typing-typeddict.pyi]
1351
1352 [case testTypedDictGetDefaultParameterStillTypeChecked]
1353 from typing import TypedDict
1354 TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
1355 p = TaggedPoint(type='2d', x=42, y=1337)
1356 p.get('x', 1 + 'y') # E: Unsupported operand types for + ("int" and "str")
1357 [builtins fixtures/dict.pyi]
1358 [typing fixtures/typing-typeddict.pyi]
1359
1360 [case testTypedDictChainedGetWithEmptyDictDefault]
1361 from typing import TypedDict
1362 C = TypedDict('C', {'a': int}, total=True)
1363 D = TypedDict('D', {'x': C, 'y': str}, total=False)
1364 d: D
1365 reveal_type(d.get('x', {})) # N: Revealed type is "TypedDict('__main__.C', {'a'?: builtins.int})"
1366 reveal_type(d.get('x', None)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int}) | None"
1367 reveal_type(d.get('x', {}).get('a')) # N: Revealed type is "builtins.int | None"
1368 reveal_type(d.get('x', {})['a']) # N: Revealed type is "builtins.int"
1369 [builtins fixtures/dict.pyi]
1370 [typing fixtures/typing-typeddict.pyi]
1371
1372
1373 [case testTypedDictChainedGetWithEmptyDictDefault2]
1374 from typing import TypedDict
1375 C = TypedDict('C', {'a': int}, total=False)
1376 D = TypedDict('D', {'x': C, 'y': str}, total=True)
1377 d: D
1378 reveal_type(d.get('x', {})) # N: Revealed type is "TypedDict('__main__.C', {'a'?: builtins.int})"
1379 reveal_type(d.get('x', None)) # N: Revealed type is "TypedDict('__main__.C', {'a'?: builtins.int})"
1380 reveal_type(d.get('x', {}).get('a')) # N: Revealed type is "builtins.int | None"
1381 reveal_type(d.get('x', {})['a']) # N: Revealed type is "builtins.int"
1382 [builtins fixtures/dict.pyi]
1383 [typing fixtures/typing-typeddict.pyi]
1384
1385
1386 [case testTypedDictChainedGetWithEmptyDictDefault3]
1387 from typing import TypedDict
1388 C = TypedDict('C', {'a': int}, total=True)
1389 D = TypedDict('D', {'x': C, 'y': str}, total=True)
1390 d: D
1391 reveal_type(d.get('x', {})) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int})"
1392 reveal_type(d.get('x', None)) # N: Revealed type is "TypedDict('__main__.C', {'a': builtins.int})"
1393 reveal_type(d.get('x', {}).get('a')) # N: Revealed type is "builtins.int"
1394 reveal_type(d.get('x', {})['a']) # N: Revealed type is "builtins.int"
1395 [builtins fixtures/dict.pyi]
1396 [typing fixtures/typing-typeddict.pyi]
1397
1398
1399 [case testTypedDictChainedGetWithEmptyDictDefault4]
1400 from typing import TypedDict
1401 C = TypedDict('C', {'a': int}, total=False)
1402 D = TypedDict('D', {'x': C, 'y': str}, total=False)
1403 d: D
1404 reveal_type(d.get('x', {})) # N: Revealed type is "TypedDict('__main__.C', {'a'?: builtins.int})"
1405 reveal_type(d.get('x', None)) # N: Revealed type is "TypedDict('__main__.C', {'a'?: builtins.int}) | None"
1406 reveal_type(d.get('x', {}).get('a')) # N: Revealed type is "builtins.int | None"
1407 reveal_type(d.get('x', {})['a']) # N: Revealed type is "builtins.int"
1408 [builtins fixtures/dict.pyi]
1409 [typing fixtures/typing-typeddict.pyi]
1410
1411
1412 [case testTypedDictGetMethodChained]
1413 # check that chaining with get like ``.get(key, {}).get(subkey, {})`` works.
1414 from typing import TypedDict, Mapping
1415 from typing_extensions import Required, NotRequired, Never
1416
1417 class Total(TypedDict, total=True): # no keys optional
1418 key_one: int
1419 key_two: str
1420
1421 class Maybe(TypedDict, total=False): # all keys are optional
1422 key_one: int
1423 key_two: str
1424
1425 class Mixed(TypedDict): # some keys optional
1426 key_one: Required[int]
1427 key_two: NotRequired[str]
1428
1429 class Config(TypedDict):
1430 required_total: Required[Total]
1431 optional_total: NotRequired[Total]
1432 required_mixed: Required[Mixed]
1433 optional_mixed: NotRequired[Mixed]
1434 required_maybe: Required[Maybe]
1435 optional_maybe: NotRequired[Maybe]
1436
1437 def test_chaining(d: Config) -> None:
1438 reveal_type( d.get("required_total", {}) ) # N: Revealed type is "TypedDict('__main__.Total', {'key_one': builtins.int, 'key_two': builtins.str})"
1439 reveal_type( d.get("optional_total", {}) ) # N: Revealed type is "TypedDict('__main__.Total', {'key_one'?: builtins.int, 'key_two'?: builtins.str})"
1440 reveal_type( d.get("required_maybe", {}) ) # N: Revealed type is "TypedDict('__main__.Maybe', {'key_one'?: builtins.int, 'key_two'?: builtins.str})"
1441 reveal_type( d.get("optional_maybe", {}) ) # N: Revealed type is "TypedDict('__main__.Maybe', {'key_one'?: builtins.int, 'key_two'?: builtins.str})"
1442 reveal_type( d.get("required_mixed", {}) ) # N: Revealed type is "TypedDict('__main__.Mixed', {'key_one': builtins.int, 'key_two'?: builtins.str})"
1443 reveal_type( d.get("optional_mixed", {}) ) # N: Revealed type is "TypedDict('__main__.Mixed', {'key_one'?: builtins.int, 'key_two'?: builtins.str})"
1444
1445 reveal_type( d.get("required_total", {}).get("key_one") ) # N: Revealed type is "builtins.int"
1446 reveal_type( d.get("required_total", {}).get("key_two") ) # N: Revealed type is "builtins.str"
1447 reveal_type( d.get("required_total", {}).get("bad_key") ) # N: Revealed type is "builtins.object"
1448 reveal_type( d.get("optional_total", {}).get("key_one") ) # N: Revealed type is "builtins.int | None"
1449 reveal_type( d.get("optional_total", {}).get("key_two") ) # N: Revealed type is "builtins.str | None"
1450 reveal_type( d.get("optional_total", {}).get("bad_key") ) # N: Revealed type is "builtins.object"
1451
1452 reveal_type( d.get("required_maybe", {}).get("key_one") ) # N: Revealed type is "builtins.int | None"
1453 reveal_type( d.get("required_maybe", {}).get("key_two") ) # N: Revealed type is "builtins.str | None"
1454 reveal_type( d.get("required_maybe", {}).get("bad_key") ) # N: Revealed type is "builtins.object"
1455 reveal_type( d.get("optional_maybe", {}).get("key_one") ) # N: Revealed type is "builtins.int | None"
1456 reveal_type( d.get("optional_maybe", {}).get("key_two") ) # N: Revealed type is "builtins.str | None"
1457 reveal_type( d.get("optional_maybe", {}).get("bad_key") ) # N: Revealed type is "builtins.object"
1458
1459 reveal_type( d.get("required_mixed", {}).get("key_one") ) # N: Revealed type is "builtins.int"
1460 reveal_type( d.get("required_mixed", {}).get("key_two") ) # N: Revealed type is "builtins.str | None"
1461 reveal_type( d.get("required_mixed", {}).get("bad_key") ) # N: Revealed type is "builtins.object"
1462 reveal_type( d.get("optional_mixed", {}).get("key_one") ) # N: Revealed type is "builtins.int | None"
1463 reveal_type( d.get("optional_mixed", {}).get("key_two") ) # N: Revealed type is "builtins.str | None"
1464 reveal_type( d.get("optional_mixed", {}).get("bad_key") ) # N: Revealed type is "builtins.object"
1465 [builtins fixtures/dict.pyi]
1466 [typing fixtures/typing-typeddict.pyi]
1467
1468
1469 [case testTypedDictGetWithNestedUnionOfTypedDicts]
1470 # https://github.com/python/mypy/issues/19902
1471 from typing import TypedDict, Union
1472 from typing_extensions import TypeAlias, NotRequired
1473 class A(TypedDict):
1474 key: NotRequired[int]
1475
1476 class B(TypedDict):
1477 key: NotRequired[int]
1478
1479 class C(TypedDict):
1480 key: NotRequired[int]
1481
1482 A_or_B: TypeAlias = Union[A, B]
1483 A_or_B_or_C: TypeAlias = Union[A_or_B, C]
1484
1485 def test(d: A_or_B_or_C) -> None:
1486 reveal_type(d.get("key")) # N: Revealed type is "builtins.int | None"
1487 [builtins fixtures/dict.pyi]
1488 [typing fixtures/typing-typeddict.pyi]
1489
1490 -- Totality (the "total" keyword argument)
1491
1492 [case testTypedDictWithTotalTrue]
1493 from typing import TypedDict
1494 D = TypedDict('D', {'x': int, 'y': str}, total=True)
1495 d: D
1496 reveal_type(d) \
1497 # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.str})"
1498 [builtins fixtures/dict.pyi]
1499 [typing fixtures/typing-typeddict.pyi]
1500
1501 [case testTypedDictWithInvalidTotalArgument]
1502 from typing import TypedDict
1503 A = TypedDict('A', {'x': int}, total=0) # E: "total" argument must be a True or False literal
1504 B = TypedDict('B', {'x': int}, total=bool) # E: "total" argument must be a True or False literal
1505 C = TypedDict('C', {'x': int}, x=False) # E: Unexpected keyword argument "x" for "TypedDict"
1506 D = TypedDict('D', {'x': int}, False) # E: Unexpected arguments to TypedDict()
1507 E = TypedDict('E', {'x': int}, total=False, x=False) # E: Unexpected keyword argument "x" for "TypedDict"
1508 [builtins fixtures/dict.pyi]
1509 [typing fixtures/typing-typeddict.pyi]
1510
1511 [case testTypedDictWithTotalFalse]
1512 from typing import TypedDict
1513 D = TypedDict('D', {'x': int, 'y': str}, total=False)
1514 def f(d: D) -> None:
1515 reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})"
1516 f({})
1517 f({'x': 1})
1518 f({'y': ''})
1519 f({'x': 1, 'y': ''})
1520 f({'x': 1, 'z': ''}) # E: Extra key "z" for TypedDict "D"
1521 f({'x': ''}) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
1522 [builtins fixtures/dict.pyi]
1523 [typing fixtures/typing-typeddict.pyi]
1524
1525 [case testTypedDictConstructorWithTotalFalse]
1526 from typing import TypedDict
1527 D = TypedDict('D', {'x': int, 'y': str}, total=False)
1528 def f(d: D) -> None: pass
1529 reveal_type(D()) # N: Revealed type is "TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})"
1530 reveal_type(D(x=1)) # N: Revealed type is "TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})"
1531 f(D(y=''))
1532 f(D(x=1, y=''))
1533 f(D(x=1, z='')) # E: Extra key "z" for TypedDict "D"
1534 f(D(x='')) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
1535 [builtins fixtures/dict.pyi]
1536 [typing fixtures/typing-typeddict.pyi]
1537
1538 [case testTypedDictIndexingWithNonRequiredKey]
1539 from typing import TypedDict
1540 D = TypedDict('D', {'x': int, 'y': str}, total=False)
1541 d: D
1542 reveal_type(d['x']) # N: Revealed type is "builtins.int"
1543 reveal_type(d['y']) # N: Revealed type is "builtins.str"
1544 reveal_type(d.get('x')) # N: Revealed type is "builtins.int | None"
1545 reveal_type(d.get('y')) # N: Revealed type is "builtins.str | None"
1546 [builtins fixtures/dict.pyi]
1547 [typing fixtures/typing-typeddict.pyi]
1548
1549 [case testTypedDictSubtypingWithTotalFalse]
1550 from typing import TypedDict
1551 A = TypedDict('A', {'x': int})
1552 B = TypedDict('B', {'x': int}, total=False)
1553 C = TypedDict('C', {'x': int, 'y': str}, total=False)
1554 def fa(a: A) -> None: pass
1555 def fb(b: B) -> None: pass
1556 def fc(c: C) -> None: pass
1557 a: A
1558 b: B
1559 c: C
1560 fb(b)
1561 fc(c)
1562 fb(c)
1563 fb(a) # E: Argument 1 to "fb" has incompatible type "A"; expected "B"
1564 fa(b) # E: Argument 1 to "fa" has incompatible type "B"; expected "A"
1565 fc(b) # E: Argument 1 to "fc" has incompatible type "B"; expected "C"
1566 [builtins fixtures/dict.pyi]
1567 [typing fixtures/typing-typeddict.pyi]
1568
1569 [case testTypedDictJoinWithTotalFalse]
1570 from typing import TypedDict, TypeVar
1571 A = TypedDict('A', {'x': int})
1572 B = TypedDict('B', {'x': int}, total=False)
1573 C = TypedDict('C', {'x': int, 'y': str}, total=False)
1574 T = TypeVar('T')
1575 def j(x: T, y: T) -> T: return x
1576 a: A
1577 b: B
1578 c: C
1579 reveal_type(j(a, b)) \
1580 # N: Revealed type is "TypedDict({'x'?=: builtins.int})"
1581 reveal_type(j(b, b)) \
1582 # N: Revealed type is "TypedDict({'x'?: builtins.int})"
1583 reveal_type(j(c, c)) \
1584 # N: Revealed type is "TypedDict({'x'?: builtins.int, 'y'?: builtins.str})"
1585 reveal_type(j(b, c)) \
1586 # N: Revealed type is "TypedDict({'x'?: builtins.int})"
1587 reveal_type(j(c, b)) \
1588 # N: Revealed type is "TypedDict({'x'?: builtins.int})"
1589 [builtins fixtures/dict.pyi]
1590 [typing fixtures/typing-typeddict.pyi]
1591
1592 [case testTypedDictClassWithTotalArgument]
1593 from typing import TypedDict
1594 class D(TypedDict, total=False):
1595 x: int
1596 y: str
1597 d: D
1598 reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})"
1599 [builtins fixtures/dict.pyi]
1600 [typing fixtures/typing-typeddict.pyi]
1601
1602 [case testTypedDictClassWithInvalidTotalArgument]
1603 from typing import TypedDict
1604 class D(TypedDict, total=1): # E: "total" argument must be a True or False literal
1605 x: int
1606 class E(TypedDict, total=bool): # E: "total" argument must be a True or False literal
1607 x: int
1608 class F(TypedDict, total=xyz): # E: Name "xyz" is not defined \
1609 # E: "total" argument must be a True or False literal
1610 x: int
1611 [builtins fixtures/dict.pyi]
1612 [typing fixtures/typing-typeddict.pyi]
1613
1614 [case testTypedDictClassInheritanceWithTotalArgument]
1615 from typing import TypedDict
1616 class A(TypedDict):
1617 x: int
1618 class B(TypedDict, A, total=False):
1619 y: int
1620 class C(TypedDict, B, total=True):
1621 z: str
1622 c: C
1623 reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'x': builtins.int, 'y'?: builtins.int, 'z': builtins.str})"
1624 [builtins fixtures/dict.pyi]
1625 [typing fixtures/typing-typeddict.pyi]
1626
1627 [case testNonTotalTypedDictInErrorMessages]
1628 from typing import TypedDict
1629
1630 A = TypedDict('A', {'x': int, 'y': str}, total=False)
1631 B = TypedDict('B', {'x': int, 'z': str, 'a': int}, total=False)
1632 C = TypedDict('C', {'x': int, 'z': str, 'a': str}, total=False)
1633 a: A
1634 b: B
1635 c: C
1636
1637 def f(a: A) -> None: pass
1638
1639 l = [a, b] # Join generates an anonymous TypedDict
1640 f(l) # E: Argument 1 to "f" has incompatible type "list[TypedDict({'x'?: int})]"; expected "A"
1641 ll = [b, c]
1642 f(ll) # E: Argument 1 to "f" has incompatible type "list[TypedDict({'x'?: int, 'z'?: str, 'a'?=: object})]"; expected "A"
1643 [builtins fixtures/dict.pyi]
1644 [typing fixtures/typing-typeddict.pyi]
1645
1646 [case testNonTotalTypedDictCanBeEmpty]
1647 # flags: --warn-unreachable
1648 from typing import TypedDict
1649
1650 class A(TypedDict):
1651 ...
1652
1653 class B(TypedDict, total=False):
1654 x: int
1655
1656 a: A = {}
1657 b: B = {}
1658
1659 if not a:
1660 reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {})"
1661
1662 if not b:
1663 reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'x'?: builtins.int})"
1664 [builtins fixtures/dict.pyi]
1665 [typing fixtures/typing-typeddict.pyi]
1666
1667 -- Create Type (Errors)
1668
1669 [case testCannotCreateTypedDictTypeWithTooFewArguments]
1670 from typing import TypedDict
1671 Point = TypedDict('Point') # E: Too few arguments for TypedDict()
1672 [builtins fixtures/dict.pyi]
1673 [typing fixtures/typing-typeddict.pyi]
1674
1675 [case testCannotCreateTypedDictTypeWithTooManyArguments]
1676 from typing import TypedDict
1677 Point = TypedDict('Point', {'x': int, 'y': int}, dict) # E: Unexpected arguments to TypedDict()
1678 [builtins fixtures/dict.pyi]
1679 [typing fixtures/typing-typeddict.pyi]
1680
1681 [case testCannotCreateTypedDictTypeWithInvalidName]
1682 from typing import TypedDict
1683 Point = TypedDict(dict, {'x': int, 'y': int}) # E: TypedDict() expects a string literal as the first argument
1684 [builtins fixtures/dict.pyi]
1685 [typing fixtures/typing-typeddict.pyi]
1686
1687 [case testCannotCreateTypedDictTypeWithInvalidItems]
1688 from typing import TypedDict
1689 Point = TypedDict('Point', {'x'}) # E: TypedDict() expects a dictionary literal as the second argument
1690 [builtins fixtures/dict.pyi]
1691 [typing fixtures/typing-typeddict.pyi]
1692
1693 [case testCannotCreateTypedDictTypeWithKwargs]
1694 from typing import TypedDict
1695 d = {'x': int, 'y': int}
1696 Point = TypedDict('Point', {**d}) # E: Invalid TypedDict() field name
1697 [builtins fixtures/dict.pyi]
1698 [typing fixtures/typing-typeddict.pyi]
1699
1700 [case testCannotCreateTypedDictTypeWithBytes]
1701 from typing import TypedDict
1702 Point = TypedDict(b'Point', {'x': int, 'y': int}) # E: TypedDict() expects a string literal as the first argument
1703 # This technically works at runtime but doesn't make sense.
1704 Point2 = TypedDict('Point2', {b'x': int}) # E: Invalid TypedDict() field name
1705 [builtins fixtures/dict.pyi]
1706 [typing fixtures/typing-typeddict.pyi]
1707
1708 -- NOTE: The following code works at runtime but is not yet supported by mypy.
1709 -- Keyword arguments may potentially be supported in the future.
1710 [case testCannotCreateTypedDictTypeWithNonpositionalArgs]
1711 from typing import TypedDict
1712 Point = TypedDict(typename='Point', fields={'x': int, 'y': int}) # E: Unexpected arguments to TypedDict()
1713 [builtins fixtures/dict.pyi]
1714 [typing fixtures/typing-typeddict.pyi]
1715
1716 [case testCannotCreateTypedDictTypeWithInvalidItemName]
1717 from typing import TypedDict
1718 Point = TypedDict('Point', {int: int, int: int}) # E: Invalid TypedDict() field name
1719 [builtins fixtures/dict.pyi]
1720 [typing fixtures/typing-typeddict.pyi]
1721
1722 [case testCannotCreateTypedDictTypeWithInvalidItemType]
1723 from typing import TypedDict
1724 Point = TypedDict('Point', {'x': 1, 'y': 1}) # E: Invalid type: try using Literal[1] instead?
1725 [builtins fixtures/dict.pyi]
1726 [typing fixtures/typing-typeddict.pyi]
1727
1728 [case testCannotCreateTypedDictTypeWithInvalidName2]
1729 from typing import TypedDict
1730 X = TypedDict('Y', {'x': int}) # E: First argument "Y" to TypedDict() does not match variable name "X"
1731 [builtins fixtures/dict.pyi]
1732 [typing fixtures/typing-typeddict.pyi]
1733
1734
1735 -- Overloading
1736
1737 [case testTypedDictOverloading]
1738 from typing import overload, Iterable, TypedDict
1739
1740 A = TypedDict('A', {'x': int})
1741
1742 @overload
1743 def f(x: Iterable[str]) -> str: ...
1744 @overload
1745 def f(x: int) -> int: ...
1746 def f(x): pass
1747
1748 a: A
1749 reveal_type(f(a)) # N: Revealed type is "builtins.str"
1750 reveal_type(f(1)) # N: Revealed type is "builtins.int"
1751 [builtins fixtures/dict.pyi]
1752 [typing fixtures/typing-typeddict.pyi]
1753
1754 [case testTypedDictOverloading2]
1755 from typing import overload, Iterable, TypedDict
1756
1757 A = TypedDict('A', {'x': int})
1758
1759 @overload
1760 def f(x: Iterable[int]) -> None: ...
1761 @overload
1762 def f(x: int) -> None: ...
1763 def f(x): pass
1764
1765 a: A
1766 f(a)
1767 [builtins fixtures/dict.pyi]
1768 [typing fixtures/typing-typeddict.pyi]
1769 [out]
1770 main:12: error: Argument 1 to "f" has incompatible type "A"; expected "Iterable[int]"
1771 main:12: note: Following member(s) of "A" have conflicts:
1772 main:12: note: Expected:
1773 main:12: note: def __iter__(self) -> Iterator[int]
1774 main:12: note: Got:
1775 main:12: note: def __iter__(self) -> Iterator[str]
1776
1777 [case testTypedDictOverloading3]
1778 from typing import TypedDict, overload
1779
1780 A = TypedDict('A', {'x': int})
1781
1782 @overload
1783 def f(x: str) -> None: ...
1784 @overload
1785 def f(x: int) -> None: ...
1786 def f(x): pass
1787
1788 a: A
1789 f(a) # E: No overload variant of "f" matches argument type "A" \
1790 # N: Possible overload variants: \
1791 # N: def f(x: str) -> None \
1792 # N: def f(x: int) -> None
1793 [builtins fixtures/dict.pyi]
1794 [typing fixtures/typing-typeddict.pyi]
1795
1796 [case testTypedDictOverloading4]
1797 from typing import TypedDict, overload
1798
1799 A = TypedDict('A', {'x': int})
1800 B = TypedDict('B', {'x': str})
1801
1802 @overload
1803 def f(x: A) -> int: ...
1804 @overload
1805 def f(x: int) -> str: ...
1806 def f(x): pass
1807
1808 a: A
1809 b: B
1810 reveal_type(f(a)) # N: Revealed type is "builtins.int"
1811 reveal_type(f(1)) # N: Revealed type is "builtins.str"
1812 f(b) # E: Argument 1 to "f" has incompatible type "B"; expected "A"
1813 [builtins fixtures/dict.pyi]
1814 [typing fixtures/typing-typeddict.pyi]
1815
1816 [case testTypedDictOverloading5]
1817 from typing import TypedDict, overload
1818
1819 A = TypedDict('A', {'x': int})
1820 B = TypedDict('B', {'y': str})
1821 C = TypedDict('C', {'y': int})
1822
1823 @overload
1824 def f(x: A) -> None: ...
1825 @overload
1826 def f(x: B) -> None: ...
1827 def f(x): pass
1828
1829 a: A
1830 b: B
1831 c: C
1832 f(a)
1833 f(b)
1834 f(c) # E: Argument 1 to "f" has incompatible type "C"; expected "A"
1835 [builtins fixtures/dict.pyi]
1836 [typing fixtures/typing-typeddict.pyi]
1837
1838 [case testTypedDictOverloading6]
1839 from typing import TypedDict, overload
1840
1841 A = TypedDict('A', {'x': int})
1842 B = TypedDict('B', {'y': str})
1843
1844 @overload
1845 def f(x: A) -> int: ...
1846 @overload
1847 def f(x: B) -> str: ...
1848 def f(x): pass
1849
1850 a: A
1851 b: B
1852 reveal_type(f(a)) # N: Revealed type is "builtins.int"
1853 reveal_type(f(b)) # N: Revealed type is "builtins.str"
1854 [builtins fixtures/dict.pyi]
1855 [typing fixtures/typing-typeddict.pyi]
1856
1857
1858 -- Special cases
1859
1860 [case testForwardReferenceInTypedDict]
1861 from typing import TypedDict, Mapping
1862 X = TypedDict('X', {'b': 'B', 'c': 'C'})
1863 class B: pass
1864 class C(B): pass
1865 x: X
1866 reveal_type(x) # N: Revealed type is "TypedDict('__main__.X', {'b': __main__.B, 'c': __main__.C})"
1867 m1: Mapping[str, object] = x
1868 m2: Mapping[str, B] = x # E: Incompatible types in assignment (expression has type "X", variable has type "Mapping[str, B]")
1869 [builtins fixtures/dict.pyi]
1870 [typing fixtures/typing-typeddict.pyi]
1871
1872 [case testForwardReferenceInClassTypedDict]
1873 from typing import TypedDict, Mapping
1874 class X(TypedDict):
1875 b: 'B'
1876 c: 'C'
1877 class B: pass
1878 class C(B): pass
1879 x: X
1880 reveal_type(x) # N: Revealed type is "TypedDict('__main__.X', {'b': __main__.B, 'c': __main__.C})"
1881 m1: Mapping[str, object] = x
1882 m2: Mapping[str, B] = x # E: Incompatible types in assignment (expression has type "X", variable has type "Mapping[str, B]")
1883 [builtins fixtures/dict.pyi]
1884 [typing fixtures/typing-typeddict.pyi]
1885
1886 [case testForwardReferenceToTypedDictInTypedDict]
1887 from typing import TypedDict, Mapping
1888 X = TypedDict('X', {'a': 'A'})
1889 A = TypedDict('A', {'b': int})
1890 x: X
1891 reveal_type(x) # N: Revealed type is "TypedDict('__main__.X', {'a': TypedDict('__main__.A', {'b': builtins.int})})"
1892 reveal_type(x['a']['b']) # N: Revealed type is "builtins.int"
1893 [builtins fixtures/dict.pyi]
1894 [typing fixtures/typing-typeddict.pyi]
1895
1896 [case testForwardReferenceInOverwrittenKey]
1897 from typing import ReadOnly, TypedDict
1898
1899 class X("XB"): pass
1900 class Y("YB"): pass
1901 class Z("ZB"): pass
1902
1903 class A(TypedDict):
1904 key: "X"
1905 class B(A):
1906 key: "Y" # E: Definition of field "key" incompatible with base class "A"
1907 class C(A):
1908 key: "Z" # E: Definition of field "key" incompatible with base class "A"
1909 class D(A):
1910 key: int # E: Definition of field "key" incompatible with base class "A"
1911
1912 class XB: pass
1913 class YB(X): pass
1914 class ZB: pass
1915 [builtins fixtures/dict.pyi]
1916 [typing fixtures/typing-typeddict.pyi]
1917
1918 [case testSelfRecursiveTypedDictInheriting]
1919 from typing import TypedDict
1920
1921 def test() -> None:
1922 class MovieBase(TypedDict):
1923 name: str
1924 year: int
1925
1926 class Movie(MovieBase):
1927 director: 'Movie' # E: Cannot resolve name "Movie" (possible cyclic definition) \
1928 # N: Recursive types are not allowed at function scope
1929 m: Movie
1930 reveal_type(m['director']['name']) # N: Revealed type is "Any"
1931 [builtins fixtures/dict.pyi]
1932 [typing fixtures/typing-typeddict.pyi]
1933
1934 [case testSubclassOfRecursiveTypedDict]
1935 from typing import List, TypedDict
1936
1937 def test() -> None:
1938 class Command(TypedDict):
1939 subcommands: List['Command'] # E: Cannot resolve name "Command" (possible cyclic definition) \
1940 # N: Recursive types are not allowed at function scope
1941
1942 class HelpCommand(Command):
1943 pass
1944
1945 hc = HelpCommand(subcommands=[])
1946 reveal_type(hc) # N: Revealed type is "TypedDict('__main__.HelpCommand@7', {'subcommands': builtins.list[Any]})"
1947 [builtins fixtures/list.pyi]
1948 [typing fixtures/typing-typeddict.pyi]
1949 [out]
1950
1951 [case testTypedDictForwardAsUpperBound]
1952 from typing import TypedDict, TypeVar, Generic
1953 T = TypeVar('T', bound='M')
1954 class G(Generic[T]):
1955 x: T
1956
1957 yb: G[int] # E: Type argument "int" of "G" must be a subtype of "M"
1958 yg: G[M]
1959 z: int = G[M]().x['x'] # type: ignore[used-before-def]
1960
1961 class M(TypedDict):
1962 x: int
1963 [builtins fixtures/dict.pyi]
1964 [typing fixtures/typing-typeddict.pyi]
1965 [out]
1966
1967 [case testTypedDictWithImportCycleForward]
1968 import a
1969 [file a.py]
1970 from typing import TypedDict
1971 from b import f
1972
1973 N = TypedDict('N', {'a': str})
1974 [file b.py]
1975 import a
1976
1977 def f(x: a.N) -> None:
1978 reveal_type(x)
1979 reveal_type(x['a'])
1980 [builtins fixtures/dict.pyi]
1981 [typing fixtures/typing-typeddict.pyi]
1982 [out]
1983 tmp/b.py:4: note: Revealed type is "TypedDict('a.N', {'a': builtins.str})"
1984 tmp/b.py:5: note: Revealed type is "builtins.str"
1985
1986 [case testTypedDictImportCycle]
1987
1988 import b
1989 [file a.py]
1990 class C:
1991 pass
1992
1993 from b import tp
1994 x: tp
1995 reveal_type(x['x']) # N: Revealed type is "builtins.int"
1996
1997 reveal_type(tp) # N: Revealed type is "def (*, x: builtins.int) -> TypedDict('b.tp', {'x': builtins.int})"
1998 tp(x='no') # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
1999
2000 [file b.py]
2001 from a import C
2002 from typing import TypedDict
2003
2004 tp = TypedDict('tp', {'x': int})
2005 [builtins fixtures/dict.pyi]
2006 [typing fixtures/typing-typeddict.pyi]
2007 [out]
2008
2009 [case testTypedDictAsStarStarArg]
2010 from typing import TypedDict
2011
2012 A = TypedDict('A', {'x': int, 'y': str})
2013 class B: pass
2014
2015 def f1(x: int, y: str) -> None: ...
2016 def f2(x: int, y: int) -> None: ...
2017 def f3(x: B, y: str) -> None: ...
2018 def f4(x: int) -> None: pass
2019 def f5(x: int, y: str, z: int) -> None: pass
2020 def f6(x: int, z: str) -> None: pass
2021
2022 a: A
2023 f1(**a)
2024 f2(**a) # E: Argument "y" to "f2" has incompatible type "str"; expected "int"
2025 f3(**a) # E: Argument "x" to "f3" has incompatible type "int"; expected "B"
2026 f4(**a) # E: Extra argument "y" from **args for "f4"
2027 f5(**a) # E: Missing positional arguments "y", "z" in call to "f5"
2028 f6(**a) # E: Extra argument "y" from **args for "f6"
2029 f1(1, **a) # E: "f1" gets multiple values for keyword argument "x"
2030 [builtins fixtures/dict.pyi]
2031 [typing fixtures/typing-typeddict.pyi]
2032
2033 [case testTypedDictAsStarStarArgConstraints]
2034 from typing import TypedDict, TypeVar, Union
2035
2036 T = TypeVar('T')
2037 S = TypeVar('S')
2038 def f1(x: T, y: S) -> Union[T, S]: ...
2039
2040 A = TypedDict('A', {'y': int, 'x': str})
2041 a: A
2042 reveal_type(f1(**a)) # N: Revealed type is "builtins.str | builtins.int"
2043 [builtins fixtures/dict.pyi]
2044 [typing fixtures/typing-typeddict.pyi]
2045
2046 [case testTypedDictAsStarStarArgCalleeKwargs]
2047 from typing import TypedDict
2048
2049 A = TypedDict('A', {'x': int, 'y': str})
2050 B = TypedDict('B', {'x': str, 'y': str})
2051
2052 def f(**kwargs: str) -> None: ...
2053 def g(x: int, **kwargs: str) -> None: ...
2054
2055 a: A
2056 b: B
2057 f(**a) # E: Argument 1 to "f" has incompatible type "**A"; expected "str"
2058 f(**b)
2059 g(**a)
2060 g(**b) # E: Argument "x" to "g" has incompatible type "str"; expected "int"
2061 g(1, **a) # E: "g" gets multiple values for keyword argument "x"
2062 g(1, **b) # E: "g" gets multiple values for keyword argument "x" \
2063 # E: Argument "x" to "g" has incompatible type "str"; expected "int"
2064 [builtins fixtures/dict.pyi]
2065 [typing fixtures/typing-typeddict.pyi]
2066
2067 [case testTypedDictAsStarStarTwice]
2068 from typing import TypedDict
2069
2070 A = TypedDict('A', {'x': int, 'y': str})
2071 B = TypedDict('B', {'z': bytes})
2072 C = TypedDict('C', {'x': str, 'z': bytes})
2073
2074 def f1(x: int, y: str, z: bytes) -> None: ...
2075 def f2(x: int, y: float, z: bytes) -> None: ...
2076 def f3(x: int, y: str, z: float) -> None: ...
2077
2078 a: A
2079 b: B
2080 c: C
2081 f1(**a, **b)
2082 f1(**b, **a)
2083 f2(**a, **b) # E: Argument "y" to "f2" has incompatible type "str"; expected "float"
2084 f3(**a, **b) # E: Argument "z" to "f3" has incompatible type "bytes"; expected "float"
2085 f3(**b, **a) # E: Argument "z" to "f3" has incompatible type "bytes"; expected "float"
2086 f1(**a, **c) # E: "f1" gets multiple values for keyword argument "x" \
2087 # E: Argument "x" to "f1" has incompatible type "str"; expected "int"
2088 f1(**c, **a) # E: "f1" gets multiple values for keyword argument "x" \
2089 # E: Argument "x" to "f1" has incompatible type "str"; expected "int"
2090 [builtins fixtures/dict.pyi]
2091 [typing fixtures/typing-typeddict.pyi]
2092
2093 [case testTypedDictAsStarStarAndDictAsStarStar]
2094 from typing import Any, Dict, TypedDict
2095
2096 TD = TypedDict('TD', {'x': int, 'y': str})
2097
2098 def f1(x: int, y: str, z: bytes) -> None: ...
2099 def f2(x: int, y: str) -> None: ...
2100
2101 td: TD
2102 d: Dict[Any, Any]
2103
2104 f1(**td, **d)
2105 f1(**d, **td)
2106 f2(**td, **d)
2107 f2(**d, **td)
2108 [builtins fixtures/dict.pyi]
2109 [typing fixtures/typing-typeddict.pyi]
2110
2111 [case testTypedDictNonMappingMethods]
2112 from typing import List, TypedDict
2113
2114 A = TypedDict('A', {'x': int, 'y': List[int]})
2115 a: A
2116
2117 reveal_type(a.copy()) # N: Revealed type is "TypedDict('__main__.A', {'x': builtins.int, 'y': builtins.list[builtins.int]})"
2118 a.has_key('x') # E: "A" has no attribute "has_key"
2119 # TODO: Better error message
2120 a.clear() # E: "A" has no attribute "clear"
2121
2122 a.setdefault('invalid', 1) # E: TypedDict "A" has no key "invalid"
2123 reveal_type(a.setdefault('x', 1)) # N: Revealed type is "builtins.int"
2124 reveal_type(a.setdefault('y', [])) # N: Revealed type is "builtins.list[builtins.int]"
2125 a.setdefault('y', '') # E: Argument 2 to "setdefault" of "TypedDict" has incompatible type "str"; expected "list[int]"
2126 x = ''
2127 a.setdefault(x, 1) # E: Expected TypedDict key to be string literal
2128 alias = a.setdefault
2129 alias(x, 1) # E: Argument 1 has incompatible type "str"; expected "Never"
2130
2131 a.update({})
2132 a.update({'x': 1})
2133 a.update({'x': ''}) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
2134 a.update({'x': 1, 'y': []})
2135 a.update({'x': 1, 'y': [1]})
2136 a.update({'z': 1}) # E: Unexpected TypedDict key "z"
2137 a.update({'z': 1, 'zz': 1}) # E: Unexpected TypedDict keys ("z", "zz")
2138 a.update({'z': 1, 'x': 1}) # E: Expected TypedDict key "x" but found keys ("z", "x")
2139 d = {'x': 1}
2140 a.update(d) # E: Argument 1 to "update" of "TypedDict" has incompatible type "dict[str, int]"; expected "TypedDict({'x'?: int, 'y'?: list[int]})"
2141 [builtins fixtures/dict.pyi]
2142 [typing fixtures/typing-typeddict.pyi]
2143
2144 [case testTypedDictPopMethod]
2145 from typing import List, TypedDict
2146
2147 A = TypedDict('A', {'x': int, 'y': List[int]}, total=False)
2148 B = TypedDict('B', {'x': int})
2149 a: A
2150 b: B
2151
2152 reveal_type(a.pop('x')) # N: Revealed type is "builtins.int"
2153 reveal_type(a.pop('y', [])) # N: Revealed type is "builtins.list[builtins.int]"
2154 reveal_type(a.pop('x', '')) # N: Revealed type is "builtins.int | Literal['']?"
2155 reveal_type(a.pop('x', (1, 2))) # N: Revealed type is "builtins.int | tuple[Literal[1]?, Literal[2]?]"
2156 a.pop('invalid', '') # E: TypedDict "A" has no key "invalid"
2157 b.pop('x') # E: Key "x" of TypedDict "B" cannot be deleted
2158 x = ''
2159 b.pop(x) # E: Expected TypedDict key to be string literal
2160 pop = b.pop
2161 pop('x') # E: Argument 1 has incompatible type "str"; expected "Never"
2162 pop('invalid') # E: Argument 1 has incompatible type "str"; expected "Never"
2163 [builtins fixtures/dict.pyi]
2164 [typing fixtures/typing-typeddict.pyi]
2165
2166 [case testTypedDictDel]
2167 from typing import List, TypedDict
2168
2169 A = TypedDict('A', {'x': int, 'y': List[int]}, total=False)
2170 B = TypedDict('B', {'x': int})
2171 a: A
2172 b: B
2173
2174 del a['x']
2175 del a['invalid'] # E: TypedDict "A" has no key "invalid"
2176 del b['x'] # E: Key "x" of TypedDict "B" cannot be deleted
2177 s = ''
2178 del a[s] # E: Expected TypedDict key to be string literal
2179 del b[s] # E: Expected TypedDict key to be string literal
2180 alias = b.__delitem__
2181 alias('x')
2182 alias(s)
2183 [builtins fixtures/dict.pyi]
2184 [typing fixtures/typing-typeddict.pyi]
2185
2186 [case testPluginUnionsOfTypedDicts]
2187 from typing import TypedDict, Union
2188
2189 class TDA(TypedDict):
2190 a: int
2191 b: str
2192
2193 class TDB(TypedDict):
2194 a: int
2195 b: int
2196 c: int
2197
2198 td: Union[TDA, TDB]
2199
2200 reveal_type(td.get('a')) # N: Revealed type is "builtins.int"
2201 reveal_type(td.get('b')) # N: Revealed type is "builtins.str | builtins.int"
2202 reveal_type(td.get('c')) # N: Revealed type is "builtins.object"
2203
2204 reveal_type(td['a']) # N: Revealed type is "builtins.int"
2205 reveal_type(td['b']) # N: Revealed type is "builtins.str | builtins.int"
2206 reveal_type(td['c']) # N: Revealed type is "Any | builtins.int" \
2207 # E: TypedDict "TDA" has no key "c"
2208 [builtins fixtures/dict.pyi]
2209 [typing fixtures/typing-typeddict.pyi]
2210
2211 [case testPluginUnionsOfTypedDictsNonTotal]
2212 from typing import TypedDict, Union
2213
2214 class TDA(TypedDict, total=False):
2215 a: int
2216 b: str
2217
2218 class TDB(TypedDict, total=False):
2219 a: int
2220 b: int
2221 c: int
2222
2223 td: Union[TDA, TDB]
2224
2225 reveal_type(td.pop('a')) # N: Revealed type is "builtins.int"
2226 reveal_type(td.pop('b')) # N: Revealed type is "builtins.str | builtins.int"
2227 reveal_type(td.pop('c')) # N: Revealed type is "Any | builtins.int" \
2228 # E: TypedDict "TDA" has no key "c"
2229
2230 [builtins fixtures/dict.pyi]
2231 [typing fixtures/typing-typeddict.pyi]
2232
2233 [case testCanCreateTypedDictWithTypingExtensions]
2234 from typing_extensions import TypedDict
2235
2236 class Point(TypedDict):
2237 x: int
2238 y: int
2239
2240 p = Point(x=42, y=1337)
2241 reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})"
2242 [builtins fixtures/dict.pyi]
2243 [typing fixtures/typing-typeddict.pyi]
2244
2245 [case testCanCreateTypedDictWithTypingProper]
2246 from typing import TypedDict
2247
2248 class Point(TypedDict):
2249 x: int
2250 y: int
2251
2252 p = Point(x=42, y=1337)
2253 reveal_type(p) # N: Revealed type is "TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})"
2254 [builtins fixtures/dict.pyi]
2255 [typing fixtures/typing-typeddict.pyi]
2256
2257 [case testTypedDictOptionalUpdate]
2258 from typing import TypedDict, Union
2259
2260 class A(TypedDict):
2261 x: int
2262
2263 d: A
2264 d.update({'x': 1})
2265 [builtins fixtures/dict.pyi]
2266 [typing fixtures/typing-typeddict.pyi]
2267
2268 [case testTypedDictOverlapWithDict]
2269 # mypy: strict-equality
2270 from typing import TypedDict, Dict
2271
2272 class Config(TypedDict):
2273 a: str
2274 b: str
2275
2276 x: Dict[str, str]
2277 y: Config
2278
2279 x == y
2280 [builtins fixtures/dict.pyi]
2281 [typing fixtures/typing-typeddict.pyi]
2282
2283 [case testTypedDictOverlapWithDictNonOverlapping]
2284 # mypy: strict-equality
2285 from typing import TypedDict, Dict
2286
2287 class Config(TypedDict):
2288 a: str
2289 b: int
2290
2291 x: Dict[str, str]
2292 y: Config
2293
2294 x == y # E: Non-overlapping equality check (left operand type: "dict[str, str]", right operand type: "Config")
2295 [builtins fixtures/dict.pyi]
2296 [typing fixtures/typing-typeddict.pyi]
2297
2298 [case testTypedDictOverlapWithDictNonTotal]
2299 # mypy: strict-equality
2300 from typing import TypedDict, Dict
2301
2302 class Config(TypedDict, total=False):
2303 a: str
2304 b: int
2305
2306 x: Dict[str, str]
2307 y: Config
2308
2309 x == y
2310 [builtins fixtures/dict.pyi]
2311 [typing fixtures/typing-typeddict.pyi]
2312
2313 [case testTypedDictOverlapWithDictNonTotalNonOverlapping]
2314 # mypy: strict-equality
2315 from typing import TypedDict, Dict
2316
2317 class Config(TypedDict, total=False):
2318 a: int
2319 b: int
2320
2321 x: Dict[str, str]
2322 y: Config
2323
2324 x == y # E: Non-overlapping equality check (left operand type: "dict[str, str]", right operand type: "Config")
2325 [builtins fixtures/dict.pyi]
2326 [typing fixtures/typing-typeddict.pyi]
2327
2328 [case testTypedDictOverlapWithDictEmpty]
2329 # mypy: strict-equality
2330 from typing import TypedDict
2331
2332 class Config(TypedDict):
2333 a: str
2334 b: str
2335
2336 x: Config
2337 x == {} # E: Non-overlapping equality check (left operand type: "Config", right operand type: "dict[Never, Never]")
2338 [builtins fixtures/dict.pyi]
2339 [typing fixtures/typing-typeddict.pyi]
2340
2341 [case testTypedDictOverlapWithDictNonTotalEmpty]
2342 # mypy: strict-equality
2343 from typing import TypedDict
2344
2345 class Config(TypedDict, total=False):
2346 a: str
2347 b: str
2348
2349 x: Config
2350 x == {}
2351 [builtins fixtures/dict.pyi]
2352 [typing fixtures/typing-typeddict.pyi]
2353
2354 [case testTypedDictOverlapWithDictNonStrKey]
2355 # mypy: strict-equality
2356 from typing import TypedDict, Dict, Union
2357
2358 class Config(TypedDict):
2359 a: str
2360 b: str
2361
2362 x: Config
2363 y: Dict[Union[str, int], str]
2364 x == y
2365 [builtins fixtures/dict.pyi]
2366 [typing fixtures/typing-typeddict.pyi]
2367
2368 [case testTypedDictOverlapWithDictOverload]
2369 from typing import overload, TypedDict, Dict
2370
2371 class Map(TypedDict):
2372 x: int
2373 y: str
2374
2375 @overload
2376 def func(x: Map) -> int: ...
2377 @overload
2378 def func(x: Dict[str, str]) -> str: ...
2379 def func(x):
2380 pass
2381 [builtins fixtures/dict.pyi]
2382 [typing fixtures/typing-typeddict.pyi]
2383
2384 [case testTypedDictOverlapWithDictOverloadBad]
2385 from typing import overload, TypedDict, Dict
2386
2387 class Map(TypedDict, total=False):
2388 x: int
2389 y: str
2390
2391 @overload
2392 def func(x: Map) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
2393 @overload
2394 def func(x: Dict[str, str]) -> str: ...
2395 def func(x):
2396 pass
2397 [builtins fixtures/dict.pyi]
2398 [typing fixtures/typing-typeddict.pyi]
2399
2400 [case testTypedDictOverlapWithDictOverloadMappingBad]
2401 from typing import overload, TypedDict, Mapping
2402
2403 class Map(TypedDict, total=False):
2404 x: int
2405 y: str
2406
2407 @overload
2408 def func(x: Map) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
2409 @overload
2410 def func(x: Mapping[str, str]) -> str: ...
2411 def func(x):
2412 pass
2413 [builtins fixtures/dict.pyi]
2414 [typing fixtures/typing-typeddict.pyi]
2415
2416 [case testTypedDictOverlapWithDictOverloadNonStrKey]
2417 from typing import overload, TypedDict, Dict
2418
2419 class Map(TypedDict):
2420 x: str
2421 y: str
2422
2423 @overload
2424 def func(x: Map) -> int: ...
2425 @overload
2426 def func(x: Dict[int, str]) -> str: ...
2427 def func(x):
2428 pass
2429 [builtins fixtures/dict.pyi]
2430 [typing fixtures/typing-typeddict.pyi]
2431
2432 [case testTypedDictIsInstance]
2433 from typing import TypedDict, Union
2434
2435 class User(TypedDict):
2436 id: int
2437 name: str
2438
2439 u: Union[str, User]
2440 u2: User
2441
2442 if isinstance(u, dict):
2443 reveal_type(u) # N: Revealed type is "TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})"
2444 else:
2445 reveal_type(u) # N: Revealed type is "builtins.str"
2446
2447 assert isinstance(u2, dict)
2448 reveal_type(u2) # N: Revealed type is "TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})"
2449 [builtins fixtures/dict.pyi]
2450 [typing fixtures/typing-typeddict.pyi]
2451
2452 [case testTypedDictIsInstanceABCs]
2453 from typing import TypedDict, Union, Mapping, Iterable
2454
2455 class User(TypedDict):
2456 id: int
2457 name: str
2458
2459 u: Union[int, User]
2460 u2: User
2461
2462 if isinstance(u, Iterable):
2463 reveal_type(u) # N: Revealed type is "TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})"
2464 else:
2465 reveal_type(u) # N: Revealed type is "builtins.int"
2466
2467 assert isinstance(u2, Mapping)
2468 reveal_type(u2) # N: Revealed type is "TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})"
2469 [builtins fixtures/dict.pyi]
2470 [typing fixtures/typing-full.pyi]
2471
2472 [case testTypedDictLiteralTypeKeyInCreation]
2473 from typing import TypedDict, Final, Literal
2474
2475 class Value(TypedDict):
2476 num: int
2477
2478 num: Final = 'num'
2479 v: Value = {num: 5}
2480 v = {num: ''} # E: Incompatible types (expression has type "str", TypedDict item "num" has type "int")
2481
2482 bad: Final = 2
2483 v = {bad: 3} # E: Expected TypedDict key to be string literal
2484 union: Literal['num', 'foo']
2485 v = {union: 2} # E: Expected TypedDict key to be string literal
2486 num2: Literal['num']
2487 v = {num2: 2}
2488 bad2: Literal['bad']
2489 v = {bad2: 2} # E: Missing key "num" for TypedDict "Value" \
2490 # E: Extra key "bad" for TypedDict "Value"
2491
2492 [builtins fixtures/dict.pyi]
2493 [typing fixtures/typing-typeddict.pyi]
2494
2495 [case testOperatorContainsNarrowsTypedDicts_unionWithList]
2496 from __future__ import annotations
2497 from typing import assert_type, TypedDict, Union
2498
2499 class D(TypedDict):
2500 foo: int
2501
2502
2503 d_or_list: D | list[str]
2504
2505 if 'foo' in d_or_list:
2506 assert_type(d_or_list, Union[D, list[str]])
2507 elif 'bar' in d_or_list:
2508 assert_type(d_or_list, list[str])
2509 else:
2510 assert_type(d_or_list, list[str])
2511
2512 [builtins fixtures/dict.pyi]
2513 [typing fixtures/typing-full.pyi]
2514
2515 [case testOperatorContainsNarrowsTypedDicts_unionWithList_final]
2516 from __future__ import annotations
2517 from typing import assert_type, final, TypedDict, Union
2518
2519 @final
2520 class D(TypedDict):
2521 foo: int
2522
2523
2524 d_or_list: D | list[str]
2525
2526 if 'foo' in d_or_list:
2527 assert_type(d_or_list, Union[D, list[str]])
2528 elif 'bar' in d_or_list:
2529 assert_type(d_or_list, list[str])
2530 else:
2531 assert_type(d_or_list, list[str])
2532
2533 [builtins fixtures/dict.pyi]
2534 [typing fixtures/typing-full.pyi]
2535
2536 [case testOperatorContainsNarrowsTypedDicts_total_never]
2537 from __future__ import annotations
2538 from typing import assert_type, final, Literal, TypedDict, TypeVar, Union
2539 from typing_extensions import Never, NotRequired
2540
2541 class D1(TypedDict):
2542 foo: int
2543 bar: NotRequired[Never]
2544 invalid: NotRequired[Never]
2545
2546 class D2(TypedDict):
2547 foo: NotRequired[Never]
2548 bar: int
2549 invalid: NotRequired[Never]
2550
2551 d: D1 | D2
2552
2553 if 'foo' in d:
2554 assert_type(d, D1)
2555 else:
2556 assert_type(d, D2)
2557
2558 foo_or_bar: Literal['foo', 'bar']
2559 if foo_or_bar in d:
2560 assert_type(d, Union[D1, D2])
2561 else:
2562 assert_type(d, Union[D1, D2])
2563
2564 foo_or_invalid: Literal['foo', 'invalid']
2565 if foo_or_invalid in d:
2566 assert_type(d, D1)
2567 # won't narrow 'foo_or_invalid'
2568 assert_type(foo_or_invalid, Literal['foo', 'invalid'])
2569 else:
2570 assert_type(d, Union[D1, D2])
2571 # won't narrow 'foo_or_invalid'
2572 assert_type(foo_or_invalid, Literal['foo', 'invalid'])
2573
2574 TD = TypeVar('TD', D1, D2)
2575
2576 def f(arg: TD) -> None:
2577 value: int
2578 if 'foo' in arg:
2579 assert_type(arg['foo'], int)
2580 else:
2581 assert_type(arg['bar'], int)
2582 [builtins fixtures/dict.pyi]
2583 [typing fixtures/typing-full.pyi]
2584
2585 [case testOperatorContainsNarrowsTypedDicts_total_final]
2586 from __future__ import annotations
2587 from typing import assert_type, final, Literal, TypedDict, TypeVar, Union
2588
2589 @final
2590 class D1(TypedDict):
2591 foo: int
2592
2593 @final
2594 class D2(TypedDict):
2595 bar: int
2596
2597 d: D1 | D2
2598
2599 if 'foo' in d:
2600 assert_type(d, D1)
2601 else:
2602 assert_type(d, D2)
2603
2604 foo_or_bar: Literal['foo', 'bar']
2605 if foo_or_bar in d:
2606 assert_type(d, Union[D1, D2])
2607 else:
2608 assert_type(d, Union[D1, D2])
2609
2610 foo_or_invalid: Literal['foo', 'invalid']
2611 if foo_or_invalid in d:
2612 assert_type(d, D1)
2613 # won't narrow 'foo_or_invalid'
2614 assert_type(foo_or_invalid, Literal['foo', 'invalid'])
2615 else:
2616 assert_type(d, Union[D1, D2])
2617 # won't narrow 'foo_or_invalid'
2618 assert_type(foo_or_invalid, Literal['foo', 'invalid'])
2619
2620 TD = TypeVar('TD', D1, D2)
2621
2622 def f(arg: TD) -> None:
2623 value: int
2624 if 'foo' in arg:
2625 assert_type(arg['foo'], int)
2626 else:
2627 assert_type(arg['bar'], int)
2628 [builtins fixtures/dict.pyi]
2629 [typing fixtures/typing-full.pyi]
2630
2631 [case testOperatorContainsNarrowsTypedDicts_never]
2632 # flags: --warn-unreachable
2633 from __future__ import annotations
2634 from typing import assert_type, TypedDict, Union
2635 from typing_extensions import Never, NotRequired
2636
2637 class DFooNotBar(TypedDict):
2638 foo: int
2639 bar: NotRequired[Never]
2640
2641
2642 class DBar(TypedDict):
2643 bar: int
2644
2645
2646 d_bar: DBar
2647
2648 if 'bar' in d_bar:
2649 assert_type(d_bar, DBar)
2650 else:
2651 spam = 'ham' # E: Statement is unreachable
2652
2653 if 'spam' in d_bar:
2654 assert_type(d_bar, DBar)
2655 else:
2656 assert_type(d_bar, DBar)
2657
2658 d_foo_not_bar: DFooNotBar
2659
2660 if 'spam' in d_foo_not_bar:
2661 spam = 'ham'
2662 else:
2663 assert_type(d_foo_not_bar, DFooNotBar)
2664
2665 d_union: DFooNotBar | DBar
2666
2667 if 'foo' in d_union:
2668 assert_type(d_union, Union[DFooNotBar, DBar])
2669 else:
2670 assert_type(d_union, DBar)
2671
2672 [builtins fixtures/dict.pyi]
2673 [typing fixtures/typing-full.pyi]
2674
2675 [case testOperatorContainsNarrowsTypedDicts_final]
2676 # flags: --warn-unreachable
2677 from __future__ import annotations
2678 from typing import assert_type, final, TypedDict, Union
2679
2680 @final
2681 class DFinal(TypedDict):
2682 foo: int
2683
2684
2685 class DNotFinal(TypedDict):
2686 bar: int
2687
2688
2689 d_not_final: DNotFinal
2690
2691 if 'bar' in d_not_final:
2692 assert_type(d_not_final, DNotFinal)
2693 else:
2694 spam = 'ham' # E: Statement is unreachable
2695
2696 if 'spam' in d_not_final:
2697 assert_type(d_not_final, DNotFinal)
2698 else:
2699 assert_type(d_not_final, DNotFinal)
2700
2701 d_final: DFinal
2702
2703 if 'spam' in d_final:
2704 spam = 'ham' # E: Statement is unreachable
2705 else:
2706 assert_type(d_final, DFinal)
2707
2708 d_union: DFinal | DNotFinal
2709
2710 if 'foo' in d_union:
2711 assert_type(d_union, Union[DFinal, DNotFinal])
2712 else:
2713 assert_type(d_union, DNotFinal)
2714
2715 [builtins fixtures/dict.pyi]
2716 [typing fixtures/typing-full.pyi]
2717
2718 [case testOperatorContainsNarrowsTypedDicts_partialThroughTotalFalse_never]
2719 from __future__ import annotations
2720 from typing import assert_type, Literal, TypedDict, Union
2721 from typing_extensions import Never, NotRequired
2722
2723 class DTotal(TypedDict):
2724 required_key: int
2725 optional_key: NotRequired[Never]
2726
2727 class DNotTotal(TypedDict, total=False):
2728 required_key: Never
2729 optional_key: int
2730
2731 d: DTotal | DNotTotal
2732
2733 if 'required_key' in d:
2734 assert_type(d, DTotal)
2735 else:
2736 assert_type(d, DNotTotal)
2737
2738 if 'optional_key' in d:
2739 assert_type(d, DNotTotal)
2740 else:
2741 assert_type(d, Union[DTotal, DNotTotal])
2742
2743 key: Literal['optional_key', 'required_key']
2744 if key in d:
2745 assert_type(d, Union[DTotal, DNotTotal])
2746 else:
2747 assert_type(d, Union[DTotal, DNotTotal])
2748
2749 [builtins fixtures/dict.pyi]
2750 [typing fixtures/typing-full.pyi]
2751
2752 [case testOperatorContainsNarrowsTypedDicts_partialThroughTotalFalse_final]
2753 from __future__ import annotations
2754 from typing import assert_type, final, Literal, TypedDict, Union
2755
2756 @final
2757 class DTotal(TypedDict):
2758 required_key: int
2759
2760 @final
2761 class DNotTotal(TypedDict, total=False):
2762 optional_key: int
2763
2764 d: DTotal | DNotTotal
2765
2766 if 'required_key' in d:
2767 assert_type(d, DTotal)
2768 else:
2769 assert_type(d, DNotTotal)
2770
2771 if 'optional_key' in d:
2772 assert_type(d, DNotTotal)
2773 else:
2774 assert_type(d, Union[DTotal, DNotTotal])
2775
2776 key: Literal['optional_key', 'required_key']
2777 if key in d:
2778 assert_type(d, Union[DTotal, DNotTotal])
2779 else:
2780 assert_type(d, Union[DTotal, DNotTotal])
2781
2782 [builtins fixtures/dict.pyi]
2783 [typing fixtures/typing-full.pyi]
2784
2785 [case testOperatorContainsNarrowsTypedDicts_partialThroughNotRequired_never]
2786 from __future__ import annotations
2787 from typing import assert_type, final, TypedDict, Union
2788 from typing_extensions import Never, Required, NotRequired
2789
2790 class D1(TypedDict):
2791 required_key: Required[int]
2792 optional_key: NotRequired[int]
2793
2794 class D2(TypedDict):
2795 abc: int
2796 xyz: int
2797 required_key: NotRequired[Never]
2798 optional_key: NotRequired[Never]
2799
2800 d: D1 | D2
2801
2802 if 'required_key' in d:
2803 assert_type(d, D1)
2804 else:
2805 assert_type(d, D2)
2806
2807 if 'optional_key' in d:
2808 assert_type(d, D1)
2809 else:
2810 assert_type(d, Union[D1, D2])
2811
2812 [builtins fixtures/dict.pyi]
2813 [typing fixtures/typing-full.pyi]
2814 [case testOperatorContainsNarrowsTypedDicts_partialThroughNotRequired_final]
2815 from __future__ import annotations
2816 from typing import assert_type, final, TypedDict, Union
2817 from typing_extensions import Required, NotRequired
2818
2819 @final
2820 class D1(TypedDict):
2821 required_key: Required[int]
2822 optional_key: NotRequired[int]
2823
2824 @final
2825 class D2(TypedDict):
2826 abc: int
2827 xyz: int
2828
2829 d: D1 | D2
2830
2831 if 'required_key' in d:
2832 assert_type(d, D1)
2833 else:
2834 assert_type(d, D2)
2835
2836 if 'optional_key' in d:
2837 assert_type(d, D1)
2838 else:
2839 assert_type(d, Union[D1, D2])
2840
2841 [builtins fixtures/dict.pyi]
2842 [typing fixtures/typing-full.pyi]
2843
2844 [case testCannotSubclassFinalTypedDict]
2845 from typing import TypedDict, final
2846
2847 @final
2848 class DummyTypedDict(TypedDict):
2849 int_val: int
2850 float_val: float
2851 str_val: str
2852
2853 class SubType(DummyTypedDict): # E: Cannot inherit from final class "DummyTypedDict"
2854 pass
2855
2856 [builtins fixtures/dict.pyi]
2857 [typing fixtures/typing-full.pyi]
2858
2859 [case testCannotSubclassFinalTypedDictWithForwardDeclarations]
2860 from typing import TypedDict, final
2861
2862 @final
2863 class DummyTypedDict(TypedDict):
2864 forward_declared: "ForwardDeclared"
2865
2866 class SubType(DummyTypedDict): # E: Cannot inherit from final class "DummyTypedDict"
2867 pass
2868
2869 class ForwardDeclared: pass
2870
2871 [builtins fixtures/dict.pyi]
2872 [typing fixtures/typing-full.pyi]
2873
2874 [case testTypedDictCannotBeDisjointBase]
2875 from typing import TypedDict
2876 from typing_extensions import disjoint_base
2877
2878 @disjoint_base # E: @disjoint_base cannot be used with TypedDict
2879 class A(TypedDict):
2880 pass
2881
2882 [builtins fixtures/dict.pyi]
2883 [typing fixtures/typing-typeddict.pyi]
2884
2885 [case testTypedDictTypeNarrowingWithFinalKey]
2886 from typing import Final, Optional, TypedDict
2887
2888 KEY_NAME: Final = "bar"
2889 class Foo(TypedDict):
2890 bar: Optional[str]
2891
2892 foo = Foo(bar="hello")
2893 if foo["bar"] is not None:
2894 reveal_type(foo["bar"]) # N: Revealed type is "builtins.str"
2895 reveal_type(foo[KEY_NAME]) # N: Revealed type is "builtins.str"
2896 if foo[KEY_NAME] is not None:
2897 reveal_type(foo["bar"]) # N: Revealed type is "builtins.str"
2898 reveal_type(foo[KEY_NAME]) # N: Revealed type is "builtins.str"
2899 [builtins fixtures/dict.pyi]
2900 [typing fixtures/typing-typeddict.pyi]
2901
2902 [case testTypedDictDoubleForwardClass]
2903 from typing import Any, List, TypedDict
2904
2905 class Foo(TypedDict):
2906 bar: Bar
2907 baz: Bar
2908
2909 Bar = List[Any]
2910
2911 foo: Foo
2912 reveal_type(foo['bar']) # N: Revealed type is "builtins.list[Any]"
2913 reveal_type(foo['baz']) # N: Revealed type is "builtins.list[Any]"
2914 [builtins fixtures/dict.pyi]
2915 [typing fixtures/typing-typeddict.pyi]
2916
2917 [case testTypedDictDoubleForwardFunc]
2918 from typing import Any, List, TypedDict
2919
2920 Foo = TypedDict('Foo', {'bar': 'Bar', 'baz': 'Bar'})
2921
2922 Bar = List[Any]
2923
2924 foo: Foo
2925 reveal_type(foo['bar']) # N: Revealed type is "builtins.list[Any]"
2926 reveal_type(foo['baz']) # N: Revealed type is "builtins.list[Any]"
2927 [builtins fixtures/dict.pyi]
2928 [typing fixtures/typing-typeddict.pyi]
2929
2930 [case testTypedDictDoubleForwardMixed]
2931 from typing import Any, List, TypedDict
2932
2933 Bar = List[Any]
2934
2935 class Foo(TypedDict):
2936 foo: Toto
2937 bar: Bar
2938 baz: Bar
2939
2940 Toto = int
2941
2942 foo: Foo
2943 reveal_type(foo['foo']) # N: Revealed type is "builtins.int"
2944 reveal_type(foo['bar']) # N: Revealed type is "builtins.list[Any]"
2945 reveal_type(foo['baz']) # N: Revealed type is "builtins.list[Any]"
2946 [builtins fixtures/dict.pyi]
2947 [typing fixtures/typing-typeddict.pyi]
2948
2949 [case testAssignTypedDictAsAttribute]
2950 from typing import TypedDict
2951
2952 class A:
2953 def __init__(self) -> None:
2954 self.b = TypedDict('b', {'x': int, 'y': str}) # E: TypedDict type as attribute is not supported
2955
2956 reveal_type(A().b) # N: Revealed type is "Any"
2957 [builtins fixtures/dict.pyi]
2958 [typing fixtures/typing-typeddict.pyi]
2959
2960 [case testTypedDictAsUpperBoundAndIndexedAssign]
2961 from typing import TypeVar, Generic, TypedDict
2962
2963
2964 class BaseDict(TypedDict, total=False):
2965 foo: int
2966
2967
2968 _DICT_T = TypeVar('_DICT_T', bound=BaseDict)
2969
2970
2971 class SomeGeneric(Generic[_DICT_T]):
2972 def __init__(self, data: _DICT_T) -> None:
2973 self._data: _DICT_T = data
2974
2975 def set_state(self) -> None:
2976 self._data['foo'] = 1
2977 [builtins fixtures/dict.pyi]
2978 [typing fixtures/typing-typeddict.pyi]
2979
2980 [case testTypedDictCreatedWithEmptyDict]
2981 from typing import TypedDict
2982
2983 class TD(TypedDict, total=False):
2984 foo: int
2985 bar: int
2986
2987 d: TD = dict()
2988 d2: TD = dict(foo=1)
2989 [builtins fixtures/dict.pyi]
2990 [typing fixtures/typing-typeddict.pyi]
2991
2992 [case testTypedDictBytesKey]
2993 from typing import TypedDict
2994
2995 class TD(TypedDict):
2996 foo: int
2997
2998 d: TD = {b'foo': 2} # E: Expected TypedDict key to be string literal
2999 d[b'foo'] = 3 # E: TypedDict key must be a string literal; expected one of ("foo") \
3000 # E: Argument 1 to "__setitem__" has incompatible type "bytes"; expected "str"
3001 d[b'foo'] # E: TypedDict key must be a string literal; expected one of ("foo")
3002 d[3] # E: TypedDict key must be a string literal; expected one of ("foo")
3003 d[True] # E: TypedDict key must be a string literal; expected one of ("foo")
3004 [builtins fixtures/dict.pyi]
3005 [typing fixtures/typing-typeddict.pyi]
3006
3007 [case testTypedDictUppercaseKey]
3008 from typing import TypedDict
3009
3010 Foo = TypedDict('Foo', {'camelCaseKey': str})
3011 value: Foo = {} # E: Missing key "camelCaseKey" for TypedDict "Foo"
3012 [builtins fixtures/dict.pyi]
3013 [typing fixtures/typing-typeddict.pyi]
3014
3015 [case testTypedDictWithDeferredFieldTypeEval]
3016 from typing import Generic, TypeVar, TypedDict, NotRequired
3017
3018 class Foo(TypedDict):
3019 y: NotRequired[int]
3020 x: Outer[Inner[ForceDeferredEval]]
3021
3022 var: Foo
3023 reveal_type(var) # N: Revealed type is "TypedDict('__main__.Foo', {'y'?: builtins.int, 'x': __main__.Outer[__main__.Inner[__main__.ForceDeferredEval]]})"
3024
3025 T1 = TypeVar("T1")
3026 class Outer(Generic[T1]): pass
3027
3028 T2 = TypeVar("T2", bound="ForceDeferredEval")
3029 class Inner(Generic[T2]): pass
3030
3031 class ForceDeferredEval: pass
3032 [builtins fixtures/dict.pyi]
3033 [typing fixtures/typing-typeddict.pyi]
3034
3035 [case testTypedDictRequiredUnimportedAny]
3036 # flags: --disallow-any-unimported
3037 from typing import NotRequired, TypedDict, ReadOnly
3038 from nonexistent import Foo # type: ignore[import-not-found]
3039 class Bar(TypedDict):
3040 foo: NotRequired[Foo] # E: Type of variable becomes "Any" due to an unfollowed import
3041 bar: ReadOnly[Foo] # E: Type of variable becomes "Any" due to an unfollowed import
3042 baz: NotRequired[ReadOnly[Foo]] # E: Type of variable becomes "Any" due to an unfollowed import
3043 [typing fixtures/typing-typeddict.pyi]
3044
3045 -- Required[]
3046
3047 [case testDoesRecognizeRequiredInTypedDictWithClass]
3048 from typing import TypedDict
3049 from typing import Required
3050 class Movie(TypedDict, total=False):
3051 title: Required[str]
3052 year: int
3053 m = Movie(title='The Matrix')
3054 m = Movie() # E: Missing key "title" for TypedDict "Movie"
3055 [typing fixtures/typing-typeddict.pyi]
3056
3057 [case testDoesRecognizeRequiredInTypedDictWithAssignment]
3058 from typing import TypedDict
3059 from typing import Required
3060 Movie = TypedDict('Movie', {
3061 'title': Required[str],
3062 'year': int,
3063 }, total=False)
3064 m = Movie(title='The Matrix')
3065 m = Movie() # E: Missing key "title" for TypedDict "Movie"
3066 [typing fixtures/typing-typeddict.pyi]
3067
3068 [case testDoesDisallowRequiredOutsideOfTypedDict]
3069 from typing import Required
3070 x: Required[int] = 42 # E: Required[] can be only used in a TypedDict definition
3071 [typing fixtures/typing-typeddict.pyi]
3072
3073 [case testDoesOnlyAllowRequiredInsideTypedDictAtTopLevel]
3074 from typing import TypedDict
3075 from typing import Union
3076 from typing import Required
3077 Movie = TypedDict('Movie', {
3078 'title': Union[
3079 Required[str], # E: Required[] can be only used in a TypedDict definition
3080 bytes
3081 ],
3082 'year': int,
3083 }, total=False)
3084 [typing fixtures/typing-typeddict.pyi]
3085
3086 [case testDoesDisallowRequiredInsideRequired]
3087 from typing import TypedDict
3088 from typing import Union
3089 from typing import Required
3090 Movie = TypedDict('Movie', {
3091 'title': Required[Union[
3092 Required[str], # E: Required[] can be only used in a TypedDict definition
3093 bytes
3094 ]],
3095 'year': int,
3096 }, total=False)
3097 [typing fixtures/typing-typeddict.pyi]
3098
3099 [case testRequiredOnlyAllowsOneItem]
3100 from typing import TypedDict
3101 from typing import Required
3102 class Movie(TypedDict, total=False):
3103 title: Required[str, bytes] # E: Required[] must have exactly one type argument
3104 year: int
3105 [typing fixtures/typing-typeddict.pyi]
3106
3107 [case testRequiredExplicitAny]
3108 # flags: --disallow-any-explicit
3109 from typing import TypedDict
3110 from typing import Required
3111 Foo = TypedDict("Foo", {"a.x": Required[int]})
3112 [typing fixtures/typing-typeddict.pyi]
3113
3114 -- NotRequired[]
3115
3116 [case testDoesRecognizeNotRequiredInTypedDictWithClass]
3117 from typing import TypedDict
3118 from typing import NotRequired
3119 class Movie(TypedDict):
3120 title: str
3121 year: NotRequired[int]
3122 m = Movie(title='The Matrix')
3123 m = Movie() # E: Missing key "title" for TypedDict "Movie"
3124 [typing fixtures/typing-typeddict.pyi]
3125
3126 [case testDoesRecognizeNotRequiredInTypedDictWithAssignment]
3127 from typing import TypedDict
3128 from typing import NotRequired
3129 Movie = TypedDict('Movie', {
3130 'title': str,
3131 'year': NotRequired[int],
3132 })
3133 m = Movie(title='The Matrix')
3134 m = Movie() # E: Missing key "title" for TypedDict "Movie"
3135 [typing fixtures/typing-typeddict.pyi]
3136
3137 [case testDoesDisallowNotRequiredOutsideOfTypedDict]
3138 from typing import NotRequired
3139 x: NotRequired[int] = 42 # E: NotRequired[] can be only used in a TypedDict definition
3140 [typing fixtures/typing-typeddict.pyi]
3141
3142 [case testDoesOnlyAllowNotRequiredInsideTypedDictAtTopLevel]
3143 from typing import TypedDict
3144 from typing import Union
3145 from typing import NotRequired
3146 Movie = TypedDict('Movie', {
3147 'title': Union[
3148 NotRequired[str], # E: NotRequired[] can be only used in a TypedDict definition
3149 bytes
3150 ],
3151 'year': int,
3152 })
3153 [typing fixtures/typing-typeddict.pyi]
3154
3155 [case testDoesDisallowNotRequiredInsideNotRequired]
3156 from typing import TypedDict
3157 from typing import Union
3158 from typing import NotRequired
3159 Movie = TypedDict('Movie', {
3160 'title': NotRequired[Union[
3161 NotRequired[str], # E: NotRequired[] can be only used in a TypedDict definition
3162 bytes
3163 ]],
3164 'year': int,
3165 })
3166 [typing fixtures/typing-typeddict.pyi]
3167
3168 [case testNotRequiredOnlyAllowsOneItem]
3169 from typing import TypedDict
3170 from typing import NotRequired
3171 class Movie(TypedDict):
3172 title: NotRequired[str, bytes] # E: NotRequired[] must have exactly one type argument
3173 year: int
3174 [typing fixtures/typing-typeddict.pyi]
3175
3176 [case testNotRequiredExplicitAny]
3177 # flags: --disallow-any-explicit
3178 from typing import TypedDict
3179 from typing import NotRequired
3180 Foo = TypedDict("Foo", {"a.x": NotRequired[int]})
3181 [typing fixtures/typing-typeddict.pyi]
3182
3183 -- Union dunders
3184
3185 [case testTypedDictUnionGetItem]
3186 from typing import TypedDict, Union
3187
3188 class Foo1(TypedDict):
3189 z: str
3190 a: int
3191 class Foo2(TypedDict):
3192 z: str
3193 b: int
3194
3195 def func(foo: Union[Foo1, Foo2]) -> str:
3196 reveal_type(foo["z"]) # N: Revealed type is "builtins.str"
3197 # ok, but type is incorrect:
3198 reveal_type(foo.__getitem__("z")) # N: Revealed type is "builtins.object"
3199
3200 reveal_type(foo["a"]) # N: Revealed type is "builtins.int | Any" \
3201 # E: TypedDict "Foo2" has no key "a"
3202 reveal_type(foo["b"]) # N: Revealed type is "Any | builtins.int" \
3203 # E: TypedDict "Foo1" has no key "b"
3204 reveal_type(foo["missing"]) # N: Revealed type is "Any" \
3205 # E: TypedDict "Foo1" has no key "missing" \
3206 # E: TypedDict "Foo2" has no key "missing"
3207 reveal_type(foo[1]) # N: Revealed type is "Any" \
3208 # E: TypedDict key must be a string literal; expected one of ("z", "a") \
3209 # E: TypedDict key must be a string literal; expected one of ("z", "b")
3210
3211 return foo["z"]
3212 [builtins fixtures/dict.pyi]
3213 [typing fixtures/typing-typeddict.pyi]
3214
3215
3216 [case testTypedDictUnionSetItem]
3217 from typing import TypedDict, Union
3218
3219 class Foo1(TypedDict):
3220 z: str
3221 a: int
3222 class Foo2(TypedDict):
3223 z: str
3224 b: int
3225
3226 def func(foo: Union[Foo1, Foo2]):
3227 foo["z"] = "a" # ok
3228 foo.__setitem__("z", "a") # ok
3229
3230 foo["z"] = 1 # E: Value of "z" has incompatible type "int"; expected "str"
3231
3232 foo["a"] = 1 # E: TypedDict "Foo2" has no key "a"
3233 foo["b"] = 2 # E: TypedDict "Foo1" has no key "b"
3234
3235 foo["missing"] = 1 # E: TypedDict "Foo1" has no key "missing" \
3236 # E: TypedDict "Foo2" has no key "missing"
3237 foo[1] = "m" # E: TypedDict key must be a string literal; expected one of ("z", "a") \
3238 # E: TypedDict key must be a string literal; expected one of ("z", "b") \
3239 # E: Argument 1 to "__setitem__" has incompatible type "int"; expected "str"
3240 [builtins fixtures/dict.pyi]
3241 [typing fixtures/typing-typeddict.pyi]
3242
3243
3244 [case testTypedDictUnionDelItem]
3245 from typing import TypedDict, Union
3246
3247 class Foo1(TypedDict):
3248 z: str
3249 a: int
3250 class Foo2(TypedDict):
3251 z: str
3252 b: int
3253
3254 def func(foo: Union[Foo1, Foo2]):
3255 del foo["z"] # E: Key "z" of TypedDict "Foo1" cannot be deleted \
3256 # E: Key "z" of TypedDict "Foo2" cannot be deleted
3257 foo.__delitem__("z") # E: Key "z" of TypedDict "Foo1" cannot be deleted \
3258 # E: Key "z" of TypedDict "Foo2" cannot be deleted
3259
3260 del foo["a"] # E: Key "a" of TypedDict "Foo1" cannot be deleted \
3261 # E: TypedDict "Foo2" has no key "a"
3262 del foo["b"] # E: TypedDict "Foo1" has no key "b" \
3263 # E: Key "b" of TypedDict "Foo2" cannot be deleted
3264
3265 del foo["missing"] # E: TypedDict "Foo1" has no key "missing" \
3266 # E: TypedDict "Foo2" has no key "missing"
3267 del foo[1] # E: Argument 1 to "__delitem__" has incompatible type "int"; expected "str" \
3268 # E: Expected TypedDict key to be string literal
3269
3270 [builtins fixtures/dict.pyi]
3271 [typing fixtures/typing-typeddict.pyi]
3272
3273
3274 [case testTypedDictTypeVarUnionSetItem]
3275 from typing import TypedDict, Union, TypeVar
3276
3277 F1 = TypeVar('F1', bound='Foo1')
3278 F2 = TypeVar('F2', bound='Foo2')
3279
3280 class Foo1(TypedDict):
3281 z: str
3282 a: int
3283 class Foo2(TypedDict):
3284 z: str
3285 b: int
3286
3287 def func(foo: Union[F1, F2]):
3288 foo["z"] = "a" # ok
3289 foo["z"] = 1 # E: Value of "z" has incompatible type "int"; expected "str"
3290
3291 foo["a"] = 1 # E: TypedDict "Foo2" has no key "a"
3292 foo["b"] = 2 # E: TypedDict "Foo1" has no key "b"
3293
3294 foo["missing"] = 1 # E: TypedDict "Foo1" has no key "missing" \
3295 # E: TypedDict "Foo2" has no key "missing"
3296 foo[1] = "m" # E: TypedDict key must be a string literal; expected one of ("z", "a") \
3297 # E: TypedDict key must be a string literal; expected one of ("z", "b") \
3298 # E: Argument 1 to "__setitem__" has incompatible type "int"; expected "str"
3299 [builtins fixtures/dict.pyi]
3300 [typing fixtures/typing-typeddict.pyi]
3301
3302 [case testGenericTypedDictCreation]
3303 from typing import TypedDict, Generic, TypeVar
3304
3305 T = TypeVar("T")
3306
3307 class TD(TypedDict, Generic[T]):
3308 key: int
3309 value: T
3310
3311 tds: TD[str]
3312 reveal_type(tds) # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.str})"
3313
3314 tdi = TD(key=0, value=0)
3315 reveal_type(tdi) # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.int})"
3316 TD[str](key=0, value=0) # E: Incompatible types (expression has type "int", TypedDict item "value" has type "str")
3317 TD[str]({"key": 0, "value": 0}) # E: Incompatible types (expression has type "int", TypedDict item "value" has type "str")
3318 [builtins fixtures/dict.pyi]
3319 [typing fixtures/typing-typeddict.pyi]
3320
3321 [case testGenericTypedDictInference]
3322 from typing import TypedDict, Generic, TypeVar, List
3323
3324 T = TypeVar("T")
3325
3326 class TD(TypedDict, Generic[T]):
3327 key: int
3328 value: T
3329
3330 def foo(x: TD[T]) -> List[T]: ...
3331
3332 reveal_type(foo(TD(key=1, value=2))) # N: Revealed type is "builtins.list[builtins.int]"
3333 reveal_type(foo({"key": 1, "value": 2})) # N: Revealed type is "builtins.list[builtins.int]"
3334 reveal_type(foo(dict(key=1, value=2))) # N: Revealed type is "builtins.list[builtins.int]"
3335 [builtins fixtures/dict.pyi]
3336 [typing fixtures/typing-typeddict.pyi]
3337
3338 [case testGenericTypedDictExtending]
3339 from typing import TypedDict, Generic, TypeVar, List
3340
3341 T = TypeVar("T")
3342 class TD(TypedDict, Generic[T]):
3343 key: int
3344 value: T
3345
3346 S = TypeVar("S")
3347 class STD(TD[List[S]]):
3348 other: S
3349
3350 std: STD[str]
3351 reveal_type(std) # N: Revealed type is "TypedDict('__main__.STD', {'key': builtins.int, 'value': builtins.list[builtins.str], 'other': builtins.str})"
3352 [builtins fixtures/dict.pyi]
3353 [typing fixtures/typing-typeddict.pyi]
3354
3355 [case testGenericTypedDictExtendingErrors]
3356 from typing import TypedDict, Generic, TypeVar
3357
3358 T = TypeVar("T")
3359 class Base(TypedDict, Generic[T]):
3360 x: T
3361 class Sub(Base[{}]): # E: Invalid TypedDict type argument \
3362 # E: Type expected within [...] \
3363 # E: Invalid base class "Base"
3364 y: int
3365 s: Sub
3366 reveal_type(s) # N: Revealed type is "TypedDict('__main__.Sub', {'y': builtins.int})"
3367
3368 class Sub2(Base[int, str]): # E: Invalid number of type arguments for "Base" \
3369 # E: "Base" expects 1 type argument, but 2 given
3370 y: int
3371 s2: Sub2
3372 reveal_type(s2) # N: Revealed type is "TypedDict('__main__.Sub2', {'x': Any, 'y': builtins.int})"
3373
3374 class Sub3(Base): # OK
3375 y: int
3376 s3: Sub3
3377 reveal_type(s3) # N: Revealed type is "TypedDict('__main__.Sub3', {'x': Any, 'y': builtins.int})"
3378 [builtins fixtures/dict.pyi]
3379 [typing fixtures/typing-typeddict.pyi]
3380
3381 [case testGenericTypedDictUpdate]
3382 from typing import TypedDict, Generic, TypeVar
3383
3384 T = TypeVar("T")
3385
3386 class Group(TypedDict, Generic[T]):
3387 a: T
3388
3389 value: Group[int] = {"a": 1}
3390
3391 def func(value2: Group[int]) -> None:
3392 value.update(value2)
3393 value.update({"a": 2})
3394 value.update({"a": "string"}) # E: Incompatible types (expression has type "str", TypedDict item "a" has type "int")
3395
3396 S = TypeVar("S")
3397
3398 class MultiField(TypedDict, Generic[T, S]):
3399 x: T
3400 y: S
3401
3402 mf1: MultiField[int, str] = {"x": 1, "y": "a"}
3403 mf2: MultiField[int, str] = {"x": 2, "y": "b"}
3404 mf1.update(mf2)
3405
3406 mf3: MultiField[str, str] = {"x": "test", "y": "c"}
3407 mf1.update(mf3) # E: Argument 1 to "update" of "TypedDict" has incompatible type "MultiField[str, str]"; expected "TypedDict({'x': int, 'y': str})"
3408
3409 mf1.update({"x": 3})
3410 mf1.update({"y": "d"})
3411 [builtins fixtures/dict.pyi]
3412 [typing fixtures/typing-typeddict.pyi]
3413
3414 [case testTypedDictAttributeOnClassObject]
3415 from typing import TypedDict
3416
3417 class TD(TypedDict):
3418 x: str
3419 y: str
3420
3421 reveal_type(TD.__iter__) # N: Revealed type is "def (typing._TypedDict) -> typing.Iterator[builtins.str]"
3422 reveal_type(TD.__annotations__) # N: Revealed type is "typing.Mapping[builtins.str, builtins.object]"
3423 reveal_type(TD.values) # N: Revealed type is "def (self: typing.Mapping[builtins.str, builtins.object]) -> typing.Iterable[builtins.object]"
3424 [builtins fixtures/dict-full.pyi]
3425 [typing fixtures/typing-typeddict.pyi]
3426
3427 [case testGenericTypedDictAlias]
3428 # flags: --disallow-any-generics
3429 from typing import TypedDict, Generic, TypeVar, List
3430
3431 T = TypeVar("T")
3432 class TD(TypedDict, Generic[T]):
3433 key: int
3434 value: T
3435
3436 Alias = TD[List[T]]
3437
3438 ad: Alias[str]
3439 reveal_type(ad) # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.list[builtins.str]})"
3440 Alias[str](key=0, value=0) # E: Incompatible types (expression has type "int", TypedDict item "value" has type "list[str]")
3441
3442 # Generic aliases are *always* filled with Any, so this is different from TD(...) call.
3443 Alias(key=0, value=0) # E: Missing type arguments for generic type "Alias" \
3444 # E: Incompatible types (expression has type "int", TypedDict item "value" has type "list[Any]")
3445
3446 [builtins fixtures/dict.pyi]
3447 [typing fixtures/typing-typeddict.pyi]
3448
3449 [case testGenericTypedDictMultipleGenerics]
3450 # See https://github.com/python/mypy/issues/13755
3451 from typing import Generic, TypeVar, TypedDict
3452
3453 T = TypeVar("T")
3454 Foo = TypedDict("Foo", {"bar": T})
3455 class Stack(Generic[T]): pass
3456
3457 a = Foo[str]
3458 b = Foo[int]
3459 reveal_type(a) # N: Revealed type is "def (*, bar: builtins.str) -> TypedDict('__main__.Foo', {'bar': builtins.str})"
3460 reveal_type(b) # N: Revealed type is "def (*, bar: builtins.int) -> TypedDict('__main__.Foo', {'bar': builtins.int})"
3461
3462 [builtins fixtures/dict.pyi]
3463 [typing fixtures/typing-typeddict.pyi]
3464
3465 [case testGenericTypedDictCallSyntax]
3466 from typing import TypedDict, TypeVar
3467
3468 T = TypeVar("T")
3469 TD = TypedDict("TD", {"key": int, "value": T})
3470 reveal_type(TD) # N: Revealed type is "def [T] (*, key: builtins.int, value: T`1) -> TypedDict('__main__.TD', {'key': builtins.int, 'value': T`1})"
3471
3472 tds: TD[str]
3473 reveal_type(tds) # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.str})"
3474
3475 tdi = TD(key=0, value=0)
3476 reveal_type(tdi) # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.int})"
3477 TD[str](key=0, value=0) # E: Incompatible types (expression has type "int", TypedDict item "value" has type "str")
3478 TD[str]({"key": 0, "value": 0}) # E: Incompatible types (expression has type "int", TypedDict item "value" has type "str")
3479 [builtins fixtures/dict.pyi]
3480 [typing fixtures/typing-typeddict.pyi]
3481
3482 [case testTypedDictSelfItemNotAllowed]
3483 from typing import Self, TypedDict, Optional
3484
3485 class TD(TypedDict):
3486 val: int
3487 next: Optional[Self] # E: Self type cannot be used in TypedDict item type
3488 TDC = TypedDict("TDC", {"val": int, "next": Optional[Self]}) # E: Self type cannot be used in TypedDict item type
3489
3490 [builtins fixtures/dict.pyi]
3491 [typing fixtures/typing-typeddict.pyi]
3492
3493 [case testUnionOfEquivalentTypedDictsInferred]
3494 from typing import TypedDict, Dict
3495
3496 D = TypedDict("D", {"foo": int}, total=False)
3497
3498 def f(d: Dict[str, D]) -> None:
3499 args = d["a"]
3500 args.update(d.get("b", {})) # OK
3501 [builtins fixtures/dict.pyi]
3502 [typing fixtures/typing-typeddict.pyi]
3503
3504 [case testUnionOfEquivalentTypedDictsDeclared]
3505 from typing import TypedDict, Union
3506
3507 class A(TypedDict, total=False):
3508 name: str
3509 class B(TypedDict, total=False):
3510 name: str
3511
3512 def foo(data: Union[A, B]) -> None: ...
3513 foo({"name": "Robert"}) # OK
3514 [builtins fixtures/dict.pyi]
3515 [typing fixtures/typing-typeddict.pyi]
3516
3517 [case testUnionOfEquivalentTypedDictsEmpty]
3518 from typing import TypedDict, Union
3519
3520 class Foo(TypedDict, total=False):
3521 foo: str
3522 class Bar(TypedDict, total=False):
3523 bar: str
3524
3525 def foo(body: Union[Foo, Bar] = {}) -> None: # OK
3526 ...
3527 [builtins fixtures/dict.pyi]
3528 [typing fixtures/typing-typeddict.pyi]
3529
3530 [case testUnionOfEquivalentTypedDictsDistinct]
3531 from typing import TypedDict, Union, Literal
3532
3533 class A(TypedDict):
3534 type: Literal['a']
3535 value: bool
3536 class B(TypedDict):
3537 type: Literal['b']
3538 value: str
3539
3540 Response = Union[A, B]
3541 def method(message: Response) -> None: ...
3542
3543 method({'type': 'a', 'value': True}) # OK
3544 method({'type': 'b', 'value': 'abc'}) # OK
3545 method({'type': 'a', 'value': 'abc'}) # E: Type of TypedDict is ambiguous, none of ("A", "B") matches cleanly \
3546 # E: Argument 1 to "method" has incompatible type "dict[str, str]"; expected "A | B"
3547 [builtins fixtures/dict.pyi]
3548 [typing fixtures/typing-typeddict.pyi]
3549
3550 [case testUnionOfEquivalentTypedDictsNested]
3551 from typing import TypedDict, Union
3552
3553 class A(TypedDict, total=False):
3554 foo: C
3555 class B(TypedDict, total=False):
3556 foo: D
3557 class C(TypedDict, total=False):
3558 c: str
3559 class D(TypedDict, total=False):
3560 d: str
3561
3562 def foo(data: Union[A, B]) -> None: ...
3563 foo({"foo": {"c": "foo"}}) # OK
3564 foo({"foo": {"e": "foo"}}) # E: Type of TypedDict is ambiguous, none of ("A", "B") matches cleanly \
3565 # E: Argument 1 to "foo" has incompatible type "dict[str, dict[str, str]]"; expected "A | B"
3566 [builtins fixtures/dict.pyi]
3567 [typing fixtures/typing-typeddict.pyi]
3568
3569 [case testTypedDictMissingEmptyKey]
3570 from typing import TypedDict
3571
3572 class A(TypedDict):
3573 my_attr_1: str
3574 my_attr_2: int
3575
3576 d: A
3577 d[''] # E: TypedDict "A" has no key ""
3578 [builtins fixtures/dict.pyi]
3579 [typing fixtures/typing-typeddict.pyi]
3580
3581 [case testTypedDictFlexibleUpdate]
3582 from typing import TypedDict
3583
3584 A = TypedDict("A", {"foo": int, "bar": int})
3585 B = TypedDict("B", {"foo": int})
3586
3587 a = A({"foo": 1, "bar": 2})
3588 b = B({"foo": 2})
3589 a.update({"foo": 2})
3590 a.update(b)
3591 a.update(a)
3592 [builtins fixtures/dict.pyi]
3593 [typing fixtures/typing-typeddict.pyi]
3594
3595 [case testTypedDictStrictUpdate]
3596 # flags: --extra-checks
3597 from typing import TypedDict
3598
3599 A = TypedDict("A", {"foo": int, "bar": int})
3600 B = TypedDict("B", {"foo": int})
3601
3602 a = A({"foo": 1, "bar": 2})
3603 b = B({"foo": 2})
3604 a.update({"foo": 2}) # OK
3605 a.update(b) # E: Argument 1 to "update" of "TypedDict" has incompatible type "B"; expected "TypedDict({'foo': int, 'bar'?: int})"
3606 a.update(a) # OK
3607 [builtins fixtures/dict.pyi]
3608 [typing fixtures/typing-typeddict.pyi]
3609
3610 [case testTypedDictFlexibleUpdateUnion]
3611 from typing import TypedDict, Union
3612
3613 A = TypedDict("A", {"foo": int, "bar": int})
3614 B = TypedDict("B", {"foo": int})
3615 C = TypedDict("C", {"bar": int})
3616
3617 a = A({"foo": 1, "bar": 2})
3618 u: Union[B, C]
3619 a.update(u)
3620 [builtins fixtures/dict.pyi]
3621 [typing fixtures/typing-typeddict.pyi]
3622
3623 [case testTypedDictFlexibleUpdateUnionExtra]
3624 from typing import TypedDict, Union
3625
3626 A = TypedDict("A", {"foo": int, "bar": int})
3627 B = TypedDict("B", {"foo": int, "extra": int})
3628 C = TypedDict("C", {"bar": int, "extra": int})
3629
3630 a = A({"foo": 1, "bar": 2})
3631 u: Union[B, C]
3632 a.update(u)
3633 [builtins fixtures/dict.pyi]
3634 [typing fixtures/typing-typeddict.pyi]
3635
3636 [case testTypedDictFlexibleUpdateUnionStrict]
3637 # flags: --extra-checks
3638 from typing import TypedDict, Union, NotRequired
3639
3640 A = TypedDict("A", {"foo": int, "bar": int})
3641 A1 = TypedDict("A1", {"foo": int, "bar": NotRequired[int]})
3642 A2 = TypedDict("A2", {"foo": NotRequired[int], "bar": int})
3643 B = TypedDict("B", {"foo": int})
3644 C = TypedDict("C", {"bar": int})
3645
3646 a = A({"foo": 1, "bar": 2})
3647 u: Union[B, C]
3648 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})"
3649 u2: Union[A1, A2]
3650 a.update(u2) # OK
3651 [builtins fixtures/dict.pyi]
3652 [typing fixtures/typing-typeddict.pyi]
3653
3654 [case testTypedDictUnpackSame]
3655 # flags: --extra-checks
3656 from typing import TypedDict
3657
3658 class Foo(TypedDict):
3659 a: int
3660 b: int
3661
3662 foo1: Foo = {"a": 1, "b": 1}
3663 foo2: Foo = {**foo1, "b": 2}
3664 foo3 = Foo(**foo1, b=2)
3665 foo4 = Foo({**foo1, "b": 2})
3666 foo5 = Foo(dict(**foo1, b=2))
3667 [builtins fixtures/dict.pyi]
3668 [typing fixtures/typing-typeddict.pyi]
3669
3670 [case testTypedDictUnpackCompatible]
3671 # flags: --extra-checks
3672 from typing import TypedDict
3673
3674 class Foo(TypedDict):
3675 a: int
3676
3677 class Bar(TypedDict):
3678 a: int
3679 b: int
3680
3681 foo: Foo = {"a": 1}
3682 bar: Bar = {**foo, "b": 2}
3683 [builtins fixtures/dict.pyi]
3684 [typing fixtures/typing-typeddict.pyi]
3685
3686 [case testTypedDictUnpackIncompatible]
3687 from typing import TypedDict
3688
3689 class Foo(TypedDict):
3690 a: int
3691 b: str
3692
3693 class Bar(TypedDict):
3694 a: int
3695 b: int
3696
3697 foo: Foo = {"a": 1, "b": "a"}
3698 bar1: Bar = {**foo, "b": 2} # Incompatible item is overridden
3699 bar2: Bar = {**foo, "a": 2} # E: Incompatible types (expression has type "str", TypedDict item "b" has type "int")
3700 [builtins fixtures/dict.pyi]
3701 [typing fixtures/typing-typeddict.pyi]
3702
3703 [case testTypedDictUnpackNotRequiredKeyIncompatible]
3704 from typing import TypedDict, NotRequired
3705
3706 class Foo(TypedDict):
3707 a: NotRequired[str]
3708
3709 class Bar(TypedDict):
3710 a: NotRequired[int]
3711
3712 foo: Foo = {}
3713 bar: Bar = {**foo} # E: Incompatible types (expression has type "str", TypedDict item "a" has type "int")
3714 [builtins fixtures/dict.pyi]
3715 [typing fixtures/typing-typeddict.pyi]
3716
3717
3718 [case testTypedDictUnpackMissingOrExtraKey]
3719 from typing import TypedDict
3720
3721 class Foo(TypedDict):
3722 a: int
3723
3724 class Bar(TypedDict):
3725 a: int
3726 b: int
3727
3728 foo1: Foo = {"a": 1}
3729 bar1: Bar = {"a": 1, "b": 1}
3730 foo2: Foo = {**bar1} # E: Extra key "b" for TypedDict "Foo"
3731 bar2: Bar = {**foo1} # E: Missing key "b" for TypedDict "Bar"
3732 [builtins fixtures/dict.pyi]
3733 [typing fixtures/typing-typeddict.pyi]
3734
3735 [case testTypedDictUnpackNotRequiredKeyExtra]
3736 from typing import TypedDict, NotRequired
3737
3738 class Foo(TypedDict):
3739 a: int
3740
3741 class Bar(TypedDict):
3742 a: int
3743 b: NotRequired[int]
3744
3745 foo1: Foo = {"a": 1}
3746 bar1: Bar = {"a": 1}
3747 foo2: Foo = {**bar1} # E: Extra key "b" for TypedDict "Foo"
3748 bar2: Bar = {**foo1}
3749 [builtins fixtures/dict.pyi]
3750 [typing fixtures/typing-typeddict.pyi]
3751
3752 [case testTypedDictUnpackRequiredKeyMissing]
3753 from typing import TypedDict, NotRequired
3754
3755 class Foo(TypedDict):
3756 a: NotRequired[int]
3757
3758 class Bar(TypedDict):
3759 a: int
3760
3761 foo: Foo = {"a": 1}
3762 bar: Bar = {**foo} # E: Missing key "a" for TypedDict "Bar"
3763 [builtins fixtures/dict.pyi]
3764 [typing fixtures/typing-typeddict.pyi]
3765
3766 [case testTypedDictUnpackMultiple]
3767 # flags: --extra-checks
3768 from typing import TypedDict
3769
3770 class Foo(TypedDict):
3771 a: int
3772
3773 class Bar(TypedDict):
3774 b: int
3775
3776 class Baz(TypedDict):
3777 a: int
3778 b: int
3779 c: int
3780
3781 foo: Foo = {"a": 1}
3782 bar: Bar = {"b": 1}
3783 baz: Baz = {**foo, **bar, "c": 1}
3784 [builtins fixtures/dict.pyi]
3785 [typing fixtures/typing-typeddict.pyi]
3786
3787 [case testTypedDictUnpackNested]
3788 from typing import TypedDict
3789
3790 class Foo(TypedDict):
3791 a: int
3792 b: int
3793
3794 class Bar(TypedDict):
3795 c: Foo
3796 d: int
3797
3798 foo: Foo = {"a": 1, "b": 1}
3799 bar: Bar = {"c": foo, "d": 1}
3800 bar2: Bar = {**bar, "c": {**bar["c"], "b": 2}, "d": 2}
3801 [builtins fixtures/dict.pyi]
3802 [typing fixtures/typing-typeddict.pyi]
3803
3804 [case testTypedDictUnpackNestedError]
3805 from typing import TypedDict
3806
3807 class Foo(TypedDict):
3808 a: int
3809 b: int
3810
3811 class Bar(TypedDict):
3812 c: Foo
3813 d: int
3814
3815 foo: Foo = {"a": 1, "b": 1}
3816 bar: Bar = {"c": foo, "d": 1}
3817 bar2: Bar = {**bar, "c": {**bar["c"], "b": "wrong"}, "d": 2} # E: Incompatible types (expression has type "str", TypedDict item "b" has type "int")
3818 [builtins fixtures/dict.pyi]
3819 [typing fixtures/typing-typeddict.pyi]
3820
3821 [case testTypedDictUnpackOverrideRequired]
3822 from typing import TypedDict
3823
3824 Details = TypedDict('Details', {'first_name': str, 'last_name': str})
3825 DetailsSubset = TypedDict('DetailsSubset', {'first_name': str, 'last_name': str}, total=False)
3826 defaults: Details = {'first_name': 'John', 'last_name': 'Luther'}
3827
3828 def generate(data: DetailsSubset) -> Details:
3829 return {**defaults, **data} # OK
3830 [builtins fixtures/dict.pyi]
3831 [typing fixtures/typing-typeddict.pyi]
3832
3833 [case testTypedDictUnpackUntypedDict]
3834 from typing import Any, Dict, TypedDict
3835
3836 class Bar(TypedDict):
3837 pass
3838
3839 foo: Dict[str, Any] = {}
3840 bar: Bar = {**foo} # E: Unsupported type "dict[str, Any]" for ** expansion in TypedDict
3841 [builtins fixtures/dict.pyi]
3842 [typing fixtures/typing-typeddict.pyi]
3843
3844 [case testTypedDictUnpackIntoUnion]
3845 from typing import TypedDict, Union
3846
3847 class Foo(TypedDict):
3848 a: int
3849
3850 class Bar(TypedDict):
3851 b: int
3852
3853 foo: Foo = {'a': 1}
3854 foo_or_bar: Union[Foo, Bar] = {**foo}
3855 [builtins fixtures/dict.pyi]
3856 [typing fixtures/typing-typeddict.pyi]
3857
3858 [case testTypedDictUnpackFromUnion]
3859 from typing import TypedDict, Union
3860
3861 class Foo(TypedDict):
3862 a: int
3863 b: int
3864
3865 class Bar(TypedDict):
3866 b: int
3867
3868 foo_or_bar: Union[Foo, Bar] = {'b': 1}
3869 foo: Bar = {**foo_or_bar} # E: Extra key "a" for TypedDict "Bar"
3870 [builtins fixtures/dict.pyi]
3871 [typing fixtures/typing-typeddict.pyi]
3872
3873 [case testTypedDictUnpackUnionRequiredMissing]
3874 from typing import TypedDict, NotRequired, Union
3875
3876 class Foo(TypedDict):
3877 a: int
3878 b: int
3879
3880 class Bar(TypedDict):
3881 a: int
3882 b: NotRequired[int]
3883
3884 foo_or_bar: Union[Foo, Bar] = {"a": 1}
3885 foo: Foo = {**foo_or_bar} # E: Missing key "b" for TypedDict "Foo"
3886 [builtins fixtures/dict.pyi]
3887 [typing fixtures/typing-typeddict.pyi]
3888
3889 [case testTypedDictUnpackInference]
3890 from typing import TypedDict, Generic, TypeVar
3891
3892 class Foo(TypedDict):
3893 a: int
3894 b: str
3895
3896 T = TypeVar("T")
3897 class TD(TypedDict, Generic[T]):
3898 a: T
3899 b: str
3900
3901 foo: Foo
3902 bar = TD(**foo)
3903 reveal_type(bar) # N: Revealed type is "TypedDict('__main__.TD', {'a': builtins.int, 'b': builtins.str})"
3904 [builtins fixtures/dict.pyi]
3905 [typing fixtures/typing-typeddict.pyi]
3906
3907 [case testTypedDictUnpackStrictMode]
3908 # flags: --extra-checks
3909 from typing import TypedDict, NotRequired
3910
3911 class Foo(TypedDict):
3912 a: int
3913
3914 class Bar(TypedDict):
3915 a: int
3916 b: NotRequired[int]
3917
3918 foo: Foo
3919 bar: Bar = {**foo} # E: Non-required key "b" not explicitly found in any ** item
3920 [builtins fixtures/dict.pyi]
3921 [typing fixtures/typing-typeddict.pyi]
3922
3923 [case testTypedDictUnpackAny]
3924 from typing import Any, TypedDict, NotRequired, Dict, Union
3925
3926 class Foo(TypedDict):
3927 a: int
3928 b: NotRequired[int]
3929
3930 x: Any
3931 y: Dict[Any, Any]
3932 z: Union[Any, Dict[Any, Any]]
3933 t1: Foo = {**x} # E: Missing key "a" for TypedDict "Foo"
3934 t2: Foo = {**y} # E: Missing key "a" for TypedDict "Foo"
3935 t3: Foo = {**z} # E: Missing key "a" for TypedDict "Foo"
3936 [builtins fixtures/dict.pyi]
3937 [typing fixtures/typing-typeddict.pyi]
3938
3939 [case testTypedDictUnpackError]
3940 from typing import TypedDict
3941
3942 class Foo(TypedDict):
3943 a: int
3944
3945 def foo(x: int) -> Foo: ...
3946
3947 f: Foo = {**foo("no")} # E: Argument 1 to "foo" has incompatible type "str"; expected "int"
3948 [builtins fixtures/dict.pyi]
3949 [typing fixtures/typing-typeddict.pyi]
3950
3951
3952 [case testTypedDictWith__or__method]
3953 from typing import Dict, TypedDict
3954
3955 class Foo(TypedDict):
3956 key: int
3957
3958 foo1: Foo = {'key': 1}
3959 foo2: Foo = {'key': 2}
3960
3961 reveal_type(foo1 | foo2) # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})"
3962 reveal_type(foo1 | {'key': 1}) # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})"
3963 reveal_type(foo1 | {'key': 'a'}) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
3964 reveal_type(foo1 | {}) # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})"
3965
3966 d1: Dict[str, int]
3967 d2: Dict[int, str]
3968
3969 reveal_type(foo1 | d1) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
3970 foo1 | d2 # E: Unsupported operand types for | ("Foo" and "dict[int, str]")
3971
3972
3973 class Bar(TypedDict):
3974 key: int
3975 value: str
3976
3977 bar: Bar
3978 reveal_type(bar | {}) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
3979 reveal_type(bar | {'key': 1, 'value': 'v'}) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
3980 reveal_type(bar | {'key': 1}) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
3981 reveal_type(bar | {'value': 'v'}) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
3982 reveal_type(bar | {'key': 'a'}) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
3983 reveal_type(bar | {'value': 1}) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
3984 reveal_type(bar | {'key': 'a', 'value': 1}) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
3985
3986 reveal_type(bar | foo1) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
3987 reveal_type(bar | d1) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
3988 bar | d2 # E: Unsupported operand types for | ("Bar" and "dict[int, str]")
3989 [builtins fixtures/dict.pyi]
3990 [typing fixtures/typing-typeddict-iror.pyi]
3991
3992 [case testTypedDictWith__or__method_error]
3993 from typing import TypedDict
3994
3995 class Foo(TypedDict):
3996 key: int
3997
3998 foo: Foo = {'key': 1}
3999 foo | 1
4000
4001 class SubDict(dict): ...
4002 reveal_type(foo | SubDict())
4003 [out]
4004 main:7: error: No overload variant of "__or__" of "TypedDict" matches argument type "int"
4005 main:7: note: Possible overload variants:
4006 main:7: note: def __or__(self, TypedDict({'key'?: int}), /) -> Foo
4007 main:7: note: def __or__(self, dict[str, Any], /) -> dict[str, object]
4008 main:10: note: Revealed type is "builtins.dict[builtins.str, builtins.object]"
4009 [builtins fixtures/dict-full.pyi]
4010 [typing fixtures/typing-typeddict-iror.pyi]
4011
4012 [case testTypedDictWith__ror__method]
4013 from typing import Dict, TypedDict
4014
4015 class Foo(TypedDict):
4016 key: int
4017
4018 foo: Foo = {'key': 1}
4019
4020 reveal_type({'key': 1} | foo) # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})"
4021 reveal_type({'key': 'a'} | foo) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
4022 reveal_type({} | foo) # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})"
4023 {1: 'a'} | foo # E: Dict entry 0 has incompatible type "int": "str"; expected "str": "Any"
4024
4025 d1: Dict[str, int]
4026 d2: Dict[int, str]
4027
4028 reveal_type(d1 | foo) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
4029 d2 | foo # E: Unsupported operand types for | ("dict[int, str]" and "Foo")
4030 1 | foo # E: No overload variant of "__ror__" of "TypedDict" matches argument type "int" \
4031 # N: Possible overload variants: \
4032 # N: def __ror__(self, TypedDict({'key'?: int}), /) -> Foo \
4033 # N: def __ror__(self, dict[str, Any], /) -> dict[str, object]
4034
4035 class Bar(TypedDict):
4036 key: int
4037 value: str
4038
4039 bar: Bar
4040 reveal_type({} | bar) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
4041 reveal_type({'key': 1, 'value': 'v'} | bar) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
4042 reveal_type({'key': 1} | bar) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
4043 reveal_type({'value': 'v'} | bar) # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
4044 reveal_type({'key': 'a'} | bar) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
4045 reveal_type({'value': 1} | bar) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
4046 reveal_type({'key': 'a', 'value': 1} | bar) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
4047
4048 reveal_type(d1 | bar) # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
4049 d2 | bar # E: Unsupported operand types for | ("dict[int, str]" and "Bar")
4050 [builtins fixtures/dict.pyi]
4051 [typing fixtures/typing-typeddict-iror.pyi]
4052
4053 [case testTypedDictWith__ior__method]
4054 from typing import Dict, TypedDict
4055
4056 class Foo(TypedDict):
4057 key: int
4058
4059 foo: Foo = {'key': 1}
4060 foo |= {'key': 2}
4061
4062 foo |= {}
4063 foo |= {'key': 'a', 'b': 'a'} # E: Expected TypedDict key "key" but found keys ("key", "b") \
4064 # E: Incompatible types (expression has type "str", TypedDict item "key" has type "int")
4065 foo |= {'b': 2} # E: Unexpected TypedDict key "b"
4066
4067 d1: Dict[str, int]
4068 d2: Dict[int, str]
4069
4070 foo |= d1 # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "dict[str, int]"; expected "TypedDict({'key'?: int})"
4071 foo |= d2 # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "dict[int, str]"; expected "TypedDict({'key'?: int})"
4072
4073
4074 class Bar(TypedDict):
4075 key: int
4076 value: str
4077
4078 bar: Bar
4079 bar |= {}
4080 bar |= {'key': 1, 'value': 'a'}
4081 bar |= {'key': 'a', 'value': 'a', 'b': 'a'} # E: Expected TypedDict keys ("key", "value") but found keys ("key", "value", "b") \
4082 # E: Incompatible types (expression has type "str", TypedDict item "key" has type "int")
4083
4084 bar |= foo
4085 bar |= d1 # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "dict[str, int]"; expected "TypedDict({'key'?: int, 'value'?: str})"
4086 bar |= d2 # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "dict[int, str]"; expected "TypedDict({'key'?: int, 'value'?: str})"
4087 [builtins fixtures/dict.pyi]
4088 [typing fixtures/typing-typeddict-iror.pyi]
4089
4090 [case testGenericTypedDictStrictOptionalExtending]
4091 from typing import Generic, TypeVar, TypedDict, Optional
4092
4093 T = TypeVar("T")
4094 class Foo(TypedDict, Generic[T], total=False):
4095 a: Optional[str]
4096 g: Optional[T]
4097
4098 class Bar(Foo[T], total=False):
4099 other: str
4100
4101 b: Bar[int]
4102 reveal_type(b["a"]) # N: Revealed type is "builtins.str | None"
4103 reveal_type(b["g"]) # N: Revealed type is "builtins.int | None"
4104 [builtins fixtures/dict.pyi]
4105 [typing fixtures/typing-typeddict.pyi]
4106
4107 [case testNoCrashOnUnImportedAnyNotRequired]
4108 # flags: --disallow-any-unimported
4109 from typing import NotRequired, Required, TypedDict
4110 from thismoduledoesntexist import T # type: ignore[import]
4111
4112 B = TypedDict("B", { # E: Type of a TypedDict key becomes "Any" due to an unfollowed import
4113 "T1": NotRequired[T],
4114 "T2": Required[T],
4115 })
4116 [builtins fixtures/dict.pyi]
4117 [typing fixtures/typing-typeddict.pyi]
4118
4119 [case testTypedDictWithClassLevelKeywords_no_native_parse]
4120 from typing import TypedDict, Generic, TypeVar
4121
4122 T = TypeVar('T')
4123
4124 class Meta(type): ...
4125
4126 class WithMetaKeyword(TypedDict, metaclass=Meta): # E: Unexpected keyword argument "metaclass" for "__init_subclass__" of "TypedDict"
4127 ...
4128
4129 class GenericWithMetaKeyword(TypedDict, Generic[T], metaclass=Meta): # E: Unexpected keyword argument "metaclass" for "__init_subclass__" of "TypedDict"
4130 ...
4131
4132 # We still don't allow this, because the implementation is much easier
4133 # and it does not make any practical sense to do it:
4134 class WithTypeMeta(TypedDict, metaclass=type): # E: Unexpected keyword argument "metaclass" for "__init_subclass__" of "TypedDict"
4135 ...
4136
4137 class OtherKeywords(TypedDict, a=1, b=2, c=3, total=True): # E: Unexpected keyword argument "a" for "__init_subclass__" of "TypedDict" \
4138 # E: Unexpected keyword argument "b" for "__init_subclass__" of "TypedDict" \
4139 # E: Unexpected keyword argument "c" for "__init_subclass__" of "TypedDict"
4140 ...
4141
4142 class TotalInTheMiddle(TypedDict, a=1, total=True, b=2, c=3): # E: Unexpected keyword argument "a" for "__init_subclass__" of "TypedDict" \
4143 # E: Unexpected keyword argument "b" for "__init_subclass__" of "TypedDict" \
4144 # E: Unexpected keyword argument "c" for "__init_subclass__" of "TypedDict"
4145 ...
4146 [builtins fixtures/dict.pyi]
4147 [typing fixtures/typing-typeddict.pyi]
4148
4149 [case testCanCreateClassWithFunctionBasedTypedDictBase]
4150 from typing import TypedDict
4151
4152 class Params(TypedDict("Params", {'x': int})):
4153 pass
4154
4155 p: Params = {'x': 2}
4156 reveal_type(p) # N: Revealed type is "TypedDict('__main__.Params', {'x': builtins.int})"
4157 [builtins fixtures/dict.pyi]
4158 [typing fixtures/typing-typeddict.pyi]
4159
4160 [case testInitTypedDictFromType]
4161 from typing import TypedDict, Type
4162 from typing_extensions import Required
4163
4164 class Point(TypedDict, total=False):
4165 x: Required[int]
4166 y: int
4167
4168 def func(cls: Type[Point]) -> None:
4169 reveal_type(cls) # N: Revealed type is "type[TypedDict('__main__.Point', {'x': builtins.int, 'y'?: builtins.int})]"
4170 cls(x=1, y=2)
4171 cls(1, 2) # E: Too many positional arguments
4172 cls(x=1)
4173 cls(y=2) # E: Missing named argument "x"
4174 cls(x=1, y=2, error="") # E: Unexpected keyword argument "error"
4175 [typing fixtures/typing-full.pyi]
4176 [builtins fixtures/tuple.pyi]
4177
4178 [case testInitTypedDictFromTypeGeneric]
4179 from typing import Generic, TypedDict, Type, TypeVar
4180 from typing_extensions import Required
4181
4182 class Point(TypedDict, total=False):
4183 x: Required[int]
4184 y: int
4185
4186 T = TypeVar("T", bound=Point)
4187
4188 class A(Generic[T]):
4189 def __init__(self, a: Type[T]) -> None:
4190 self.a = a
4191
4192 def func(self) -> T:
4193 reveal_type(self.a) # N: Revealed type is "type[T`1]"
4194 self.a(x=1, y=2)
4195 self.a(y=2) # E: Missing named argument "x"
4196 return self.a(x=1)
4197 [typing fixtures/typing-full.pyi]
4198 [builtins fixtures/tuple.pyi]
4199
4200 [case testNameUndefinedErrorDoesNotLoseUnpackedKWArgsInformation]
4201 from typing import TypedDict, overload
4202 from typing_extensions import Unpack
4203
4204 class TD(TypedDict, total=False):
4205 x: int
4206 y: str
4207
4208 @overload
4209 def f(self, *, x: int) -> None: ...
4210 @overload
4211 def f(self, *, y: str) -> None: ...
4212 def f(self, **kwargs: Unpack[TD]) -> None:
4213 z # E: Name "z" is not defined
4214
4215 @overload
4216 def g(self, *, x: float) -> None: ...
4217 @overload
4218 def g(self, *, y: str) -> None: ...
4219 def g(self, **kwargs: Unpack[TD]) -> None: # E: Overloaded function implementation does not accept all possible parameters of signature 1
4220 z # E: Name "z" is not defined
4221
4222 class A:
4223 def f(self, *, x: int) -> None: ...
4224 def g(self, *, x: float) -> None: ...
4225 class B(A):
4226 def f(self, **kwargs: Unpack[TD]) -> None:
4227 z # E: Name "z" is not defined
4228 def g(self, **kwargs: Unpack[TD]) -> None: # E: Signature of "g" incompatible with supertype "A" \
4229 # N: Superclass: \
4230 # N: def g(self, *, x: float) -> None \
4231 # N: Subclass: \
4232 # N: def g(*, x: int = ..., y: str = ...) -> None
4233 z # E: Name "z" is not defined
4234 reveal_type(B.f) # N: Revealed type is "def (self: __main__.B, **kwargs: Unpack[TypedDict('__main__.TD', {'x'?: builtins.int, 'y'?: builtins.str})])"
4235 B().f(x=1.0) # E: Argument "x" to "f" of "B" has incompatible type "float"; expected "int"
4236 [builtins fixtures/primitives.pyi]
4237 [typing fixtures/typing-typeddict.pyi]
4238
4239 [case testTypedDictUnpackWithParamSpecInference]
4240 from typing import TypedDict, TypeVar, ParamSpec, Callable
4241 from typing_extensions import Unpack
4242
4243 P = ParamSpec("P")
4244 R = TypeVar("R")
4245
4246 def run(func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: ...
4247
4248 class Params(TypedDict):
4249 temperature: float
4250
4251 def test(temperature: int) -> None: ...
4252 def test2(temperature: float, other: str) -> None: ...
4253
4254 class Test:
4255 def f(self, c: Callable[..., None], **params: Unpack[Params]) -> None:
4256 run(c, **params)
4257 def g(self, **params: Unpack[Params]) -> None:
4258 run(test, **params) # E: Argument "temperature" to "run" has incompatible type "float"; expected "int"
4259 def h(self, **params: Unpack[Params]) -> None:
4260 run(test2, other="yes", **params)
4261 run(test2, other=0, **params) # E: Argument "other" to "run" has incompatible type "int"; expected "str"
4262 [builtins fixtures/dict.pyi]
4263 [typing fixtures/typing-full.pyi]
4264
4265 [case testTypedDictUnpackSingleWithSubtypingNoCrash]
4266 from typing import Callable, TypedDict
4267 from typing_extensions import Unpack
4268
4269 class Kwargs(TypedDict):
4270 name: str
4271
4272 def f(**kwargs: Unpack[Kwargs]) -> None:
4273 pass
4274
4275 class C:
4276 d: Callable[[Unpack[Kwargs]], None]
4277
4278 # TODO: it is an old question whether we should allow this, for now simply don't crash.
4279 class D(C):
4280 d = f
4281 [builtins fixtures/dict.pyi]
4282 [typing fixtures/typing-typeddict.pyi]
4283
4284 [case testTypedDictInlineNoOldStyleAlias]
4285 # flags: --enable-incomplete-feature=InlineTypedDict
4286 X = {"int": int, "str": str}
4287 reveal_type(X) # N: Revealed type is "builtins.dict[builtins.str, def () -> builtins.object]"
4288 [builtins fixtures/dict.pyi]
4289 [typing fixtures/typing-typeddict.pyi]
4290
4291 [case testTypedDictInlineYesMidStyleAlias]
4292 # flags: --enable-incomplete-feature=InlineTypedDict
4293 from typing_extensions import TypeAlias
4294 X: TypeAlias = {"int": int, "str": str}
4295 x: X
4296 reveal_type(x) # N: # N: Revealed type is "TypedDict({'int': builtins.int, 'str': builtins.str})"
4297 [builtins fixtures/dict.pyi]
4298 [typing fixtures/typing-typeddict.pyi]
4299
4300 [case testTypedDictInlineNoEmpty]
4301 # flags: --enable-incomplete-feature=InlineTypedDict
4302 x: {} # E: Invalid type comment or annotation
4303 reveal_type(x) # N: Revealed type is "Any"
4304 [builtins fixtures/dict.pyi]
4305 [typing fixtures/typing-typeddict.pyi]
4306
4307 [case testTypedDictInlineNotRequired]
4308 # flags: --enable-incomplete-feature=InlineTypedDict
4309 from typing import NotRequired
4310
4311 x: {"one": int, "other": NotRequired[int]}
4312 x = {"one": 1} # OK
4313 y: {"one": int, "other": int}
4314 y = {"one": 1} # E: Expected TypedDict keys ("one", "other") but found only key "one"
4315 [builtins fixtures/dict.pyi]
4316 [typing fixtures/typing-typeddict.pyi]
4317
4318 [case testTypedDictInlineReadOnly]
4319 # flags: --enable-incomplete-feature=InlineTypedDict
4320 from typing import ReadOnly
4321
4322 x: {"one": int, "other": ReadOnly[int]}
4323 x["one"] = 1 # ok
4324 x["other"] = 1 # E: ReadOnly TypedDict key "other" TypedDict is mutated
4325 [builtins fixtures/dict.pyi]
4326 [typing fixtures/typing-typeddict.pyi]
4327
4328 [case testTypedDictInlineNestedSchema]
4329 # flags: --enable-incomplete-feature=InlineTypedDict
4330 def nested() -> {"one": str, "other": {"a": int, "b": int}}:
4331 if bool():
4332 return {"one": "yes", "other": {"a": 1, "b": 2}} # OK
4333 else:
4334 return {"one": "no", "other": {"a": 1, "b": "2"}} # E: Incompatible types (expression has type "str", TypedDict item "b" has type "int")
4335 [builtins fixtures/dict.pyi]
4336 [typing fixtures/typing-typeddict.pyi]
4337
4338 [case testTypedDictInlineMergeAnother]
4339 # flags: --enable-incomplete-feature=InlineTypedDict
4340 from typing import TypeVar
4341 from typing_extensions import TypeAlias
4342
4343 T = TypeVar("T")
4344 X: TypeAlias = {"item": T}
4345 x: {"a": int, **X[str], "b": int}
4346 reveal_type(x) # N: Revealed type is "TypedDict({'a': builtins.int, 'b': builtins.int, 'item': builtins.str})"
4347 [builtins fixtures/dict.pyi]
4348 [typing fixtures/typing-full.pyi]
4349
4350
4351 # ReadOnly
4352 # See: https://peps.python.org/pep-0705
4353
4354 [case testTypedDictReadOnly]
4355 # flags: --show-error-codes
4356 from typing import ReadOnly, TypedDict
4357
4358 class TP(TypedDict):
4359 one: int
4360 other: ReadOnly[str]
4361
4362 x: TP
4363 reveal_type(x["one"]) # N: Revealed type is "builtins.int"
4364 reveal_type(x["other"]) # N: Revealed type is "builtins.str"
4365 x["one"] = 1 # ok
4366 x["other"] = "a" # E: ReadOnly TypedDict key "other" TypedDict is mutated [typeddict-readonly-mutated]
4367 [builtins fixtures/dict.pyi]
4368 [typing fixtures/typing-typeddict.pyi]
4369
4370 [case testTypedDictFunctionalSyntaxWithMultipleSpecialForms]
4371 from typing import ReadOnly, Required, NotRequired, TypedDict
4372 from typing_extensions import Annotated
4373 D1 = TypedDict("D1", {"x": int, "y": ReadOnly[Required[int]]}, total=False)
4374 D2 = TypedDict("D2", {"x": int, "y": Required[ReadOnly[int]]}, total=False)
4375 D3 = TypedDict("D3", {"x": int, "y": ReadOnly[NotRequired[int]]})
4376 D4 = TypedDict("D4", {"x": int, "y": NotRequired[ReadOnly[int]]})
4377 D5 = TypedDict("D5", {"x": int, "y": Annotated[ReadOnly[int], "some annotation text"]})
4378 D6 = TypedDict("D6", {"x": int, "y": ReadOnly[Annotated[int, "some annotation text"]]})
4379 D7 = TypedDict("D7", {"x": int, "y": Annotated[ReadOnly[NotRequired[int]], "some annotation text"]})
4380 D8 = TypedDict("D8", {"x": int, "y": NotRequired[ReadOnly[Annotated[int, "some annotation text"]]]})
4381 d1: D1
4382 d2: D2
4383 d3: D3
4384 d4: D4
4385 d5: D5
4386 d6: D6
4387 d7: D7
4388 d8: D8
4389 reveal_type(d1) # N: Revealed type is "TypedDict('__main__.D1', {'x'?: builtins.int, 'y'=: builtins.int})"
4390 reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'x'?: builtins.int, 'y'=: builtins.int})"
4391 reveal_type(d3) # N: Revealed type is "TypedDict('__main__.D3', {'x': builtins.int, 'y'?=: builtins.int})"
4392 reveal_type(d4) # N: Revealed type is "TypedDict('__main__.D4', {'x': builtins.int, 'y'?=: builtins.int})"
4393 reveal_type(d5) # N: Revealed type is "TypedDict('__main__.D5', {'x': builtins.int, 'y'=: builtins.int})"
4394 reveal_type(d6) # N: Revealed type is "TypedDict('__main__.D6', {'x': builtins.int, 'y'=: builtins.int})"
4395 reveal_type(d7) # N: Revealed type is "TypedDict('__main__.D7', {'x': builtins.int, 'y'?=: builtins.int})"
4396 reveal_type(d8) # N: Revealed type is "TypedDict('__main__.D8', {'x': builtins.int, 'y'?=: builtins.int})"
4397 [builtins fixtures/dict.pyi]
4398 [typing fixtures/typing-typeddict.pyi]
4399
4400 [case testTypedDictFunctionalSyntaxWithContradictorySpecialForms]
4401 from typing import Required, NotRequired, TypedDict
4402 D1 = TypedDict("D1", {"x": NotRequired[Required[int]]}) # E: "Required[]" type cannot be nested
4403 D2 = TypedDict("D2", {"x": Required[NotRequired[int]]}) # E: "NotRequired[]" type cannot be nested
4404 [builtins fixtures/dict.pyi]
4405 [typing fixtures/typing-typeddict.pyi]
4406
4407 [case testTypedDictReadOnlyCreation]
4408 from typing import ReadOnly, TypedDict
4409
4410 class TD(TypedDict):
4411 x: ReadOnly[int]
4412 y: int
4413
4414 # Ok:
4415 x = TD({"x": 1, "y": 2})
4416 y = TD(x=1, y=2)
4417 z: TD = {"x": 1, "y": 2}
4418
4419 # Error:
4420 x2 = TD({"x": "a", "y": 2}) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
4421 y2 = TD(x="a", y=2) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
4422 z2: TD = {"x": "a", "y": 2} # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
4423 [builtins fixtures/dict.pyi]
4424 [typing fixtures/typing-typeddict.pyi]
4425
4426 [case testTypedDictReadOnlyDel]
4427 from typing import ReadOnly, TypedDict, NotRequired
4428
4429 class TP(TypedDict):
4430 required_key: ReadOnly[str]
4431 optional_key: ReadOnly[NotRequired[str]]
4432
4433 x: TP
4434 del x["required_key"] # E: Key "required_key" of TypedDict "TP" cannot be deleted
4435 del x["optional_key"] # E: Key "optional_key" of TypedDict "TP" cannot be deleted
4436 [builtins fixtures/dict.pyi]
4437 [typing fixtures/typing-typeddict.pyi]
4438
4439 [case testTypedDictReadOnlyMutateMethods]
4440 from typing import ReadOnly, NotRequired, TypedDict
4441
4442 class TP(TypedDict):
4443 key: ReadOnly[str]
4444 optional_key: ReadOnly[NotRequired[str]]
4445 other: ReadOnly[int]
4446 mutable: bool
4447
4448 x: TP
4449 reveal_type(x.pop("key")) # N: Revealed type is "builtins.str" \
4450 # E: Key "key" of TypedDict "TP" cannot be deleted
4451 reveal_type(x.pop("optional_key")) # N: Revealed type is "builtins.str" \
4452 # E: Key "optional_key" of TypedDict "TP" cannot be deleted
4453
4454
4455 x.update({"key": "abc", "other": 1, "mutable": True}) # E: ReadOnly TypedDict keys ("key", "other") TypedDict are mutated
4456 x.setdefault("key", "abc") # E: ReadOnly TypedDict key "key" TypedDict is mutated
4457 x.setdefault("optional_key", "foo") # E: ReadOnly TypedDict key "optional_key" TypedDict is mutated
4458 x.setdefault("other", 1) # E: ReadOnly TypedDict key "other" TypedDict is mutated
4459 x.setdefault("mutable", False) # ok
4460 [builtins fixtures/dict.pyi]
4461 [typing fixtures/typing-typeddict.pyi]
4462
4463 [case testTypedDictFromTypingExtensionsReadOnlyMutateMethods]
4464 from typing_extensions import ReadOnly, TypedDict
4465
4466 class TP(TypedDict):
4467 key: ReadOnly[str]
4468
4469 x: TP
4470 x.update({"key": "abc"}) # E: ReadOnly TypedDict key "key" TypedDict is mutated
4471 [builtins fixtures/dict.pyi]
4472 [typing fixtures/typing-typeddict.pyi]
4473
4474 [case testTypedDictFromMypyExtensionsReadOnlyMutateMethods]
4475 from mypy_extensions import TypedDict
4476 from typing_extensions import ReadOnly
4477
4478 class TP(TypedDict):
4479 key: ReadOnly[str]
4480
4481 x: TP
4482 x.update({"key": "abc"}) # E: ReadOnly TypedDict key "key" TypedDict is mutated
4483 [builtins fixtures/dict.pyi]
4484 [typing fixtures/typing-typeddict.pyi]
4485
4486 [case testTypedDictReadOnlyMutate__ior__Statements]
4487 from typing import TypedDict
4488 from typing_extensions import ReadOnly
4489
4490 class TP(TypedDict):
4491 key: ReadOnly[str]
4492 other: ReadOnly[int]
4493 mutable: bool
4494
4495 x: TP
4496 x |= {"mutable": True} # ok
4497 x |= {"key": "a"} # E: ReadOnly TypedDict key "key" TypedDict is mutated
4498 x |= {"key": "a", "other": 1, "mutable": True} # E: ReadOnly TypedDict keys ("key", "other") TypedDict are mutated
4499 [builtins fixtures/dict.pyi]
4500 [typing fixtures/typing-typeddict-iror.pyi]
4501
4502 [case testTypedDictReadOnlyMutate__or__Statements]
4503 from typing import TypedDict
4504 from typing_extensions import ReadOnly
4505
4506 class TP(TypedDict):
4507 key: ReadOnly[str]
4508 other: ReadOnly[int]
4509 mutable: bool
4510
4511 x: TP
4512 # These are new objects, not mutation:
4513 x = x | {"mutable": True}
4514 x = x | {"key": "a"}
4515 x = x | {"key": "a", "other": 1, "mutable": True}
4516 y1 = x | {"mutable": True}
4517 y2 = x | {"key": "a"}
4518 [builtins fixtures/dict.pyi]
4519 [typing fixtures/typing-typeddict-iror.pyi]
4520
4521 [case testTypedDictReadOnlyMutateWithOtherDicts]
4522 from typing import ReadOnly, TypedDict, Dict
4523
4524 class TP(TypedDict):
4525 key: ReadOnly[str]
4526 mutable: bool
4527
4528 class Mutable(TypedDict):
4529 mutable: bool
4530
4531 class Regular(TypedDict):
4532 key: str
4533
4534 m: Mutable
4535 r: Regular
4536 d: Dict[str, object]
4537
4538 # Creating new objects is ok:
4539 tp: TP = {**r, **m}
4540 tp1: TP = {**tp, **m}
4541 tp2: TP = {**r, **m}
4542 tp3: TP = {**tp, **r}
4543 tp4: TP = {**tp, **d} # E: Unsupported type "dict[str, object]" for ** expansion in TypedDict
4544 [builtins fixtures/dict.pyi]
4545 [typing fixtures/typing-typeddict.pyi]
4546
4547 [case testTypedDictGenericReadOnly]
4548 from typing import ReadOnly, TypedDict, TypeVar, Generic
4549
4550 T = TypeVar('T')
4551
4552 class TP(TypedDict, Generic[T]):
4553 key: ReadOnly[T]
4554
4555 x: TP[int]
4556 reveal_type(x["key"]) # N: Revealed type is "builtins.int"
4557 x["key"] = 1 # E: ReadOnly TypedDict key "key" TypedDict is mutated
4558 x["key"] = "a" # E: ReadOnly TypedDict key "key" TypedDict is mutated \
4559 # E: Value of "key" has incompatible type "str"; expected "int"
4560 [builtins fixtures/dict.pyi]
4561 [typing fixtures/typing-typeddict.pyi]
4562
4563 [case testTypedDictReadOnlyOtherTypedDict]
4564 from typing import ReadOnly, TypedDict
4565
4566 class First(TypedDict):
4567 field: int
4568
4569 class TP(TypedDict):
4570 key: ReadOnly[First]
4571
4572 x: TP
4573 reveal_type(x["key"]["field"]) # N: Revealed type is "builtins.int"
4574 x["key"]["field"] = 1 # ok
4575 x["key"] = {"field": 2} # E: ReadOnly TypedDict key "key" TypedDict is mutated
4576 [builtins fixtures/dict.pyi]
4577 [typing fixtures/typing-typeddict.pyi]
4578
4579 [case testTypedDictReadOnlyInheritance]
4580 from typing import ReadOnly, TypedDict
4581
4582 class Base(TypedDict):
4583 a: ReadOnly[str]
4584
4585 class Child(Base):
4586 b: ReadOnly[int]
4587
4588 base: Base
4589 reveal_type(base["a"]) # N: Revealed type is "builtins.str"
4590 base["a"] = "x" # E: ReadOnly TypedDict key "a" TypedDict is mutated
4591 base["b"] # E: TypedDict "Base" has no key "b"
4592
4593 child: Child
4594 reveal_type(child["a"]) # N: Revealed type is "builtins.str"
4595 reveal_type(child["b"]) # N: Revealed type is "builtins.int"
4596 child["a"] = "x" # E: ReadOnly TypedDict key "a" TypedDict is mutated
4597 child["b"] = 1 # E: ReadOnly TypedDict key "b" TypedDict is mutated
4598 [builtins fixtures/dict.pyi]
4599 [typing fixtures/typing-typeddict.pyi]
4600
4601 [case testTypedDictReadOnlySubtyping]
4602 from typing import ReadOnly, TypedDict
4603
4604 class A(TypedDict):
4605 key: ReadOnly[str]
4606
4607 class B(TypedDict):
4608 key: str
4609
4610 a: A
4611 b: B
4612
4613 def accepts_A(d: A): ...
4614 def accepts_B(d: B): ...
4615
4616 accepts_A(a)
4617 accepts_A(b)
4618 accepts_B(a) # E: Argument 1 to "accepts_B" has incompatible type "A"; expected "B"
4619 accepts_B(b)
4620 [builtins fixtures/dict.pyi]
4621 [typing fixtures/typing-typeddict.pyi]
4622
4623 [case testTypedDictReadOnlyTypeVarBoundSubtyping]
4624 from typing import ReadOnly, TypedDict, TypeVar
4625 A = TypedDict('A', {'x': ReadOnly[int]})
4626 B = TypedDict('B', {'x': int})
4627 TA = TypeVar('TA', bound=A)
4628 TB = TypeVar('TB', bound=B)
4629 def fA(t: TA) -> TA: return t
4630 def fB(t: TB) -> TB: return t
4631 a: A
4632 b: B
4633 fA(a)
4634 fA(b)
4635 fB(a) # E: Value of type variable "TB" of "fB" cannot be "A"
4636 fB(b)
4637 [builtins fixtures/dict.pyi]
4638 [typing fixtures/typing-typeddict.pyi]
4639
4640 [case testTypedDictReadOnlySubclassing]
4641 from typing import ReadOnly, TypedDict
4642
4643 class A(TypedDict):
4644 key: ReadOnly[str]
4645
4646 class B(A):
4647 key: str
4648
4649 a: A
4650 b: B
4651
4652 def accepts_A(d: A): ...
4653 def accepts_B(d: B): ...
4654
4655 accepts_A(a)
4656 accepts_A(b)
4657 accepts_B(a) # E: Argument 1 to "accepts_B" has incompatible type "A"; expected "B"
4658 accepts_B(b)
4659 [builtins fixtures/dict.pyi]
4660 [typing fixtures/typing-typeddict.pyi]
4661
4662 [case testTypedDictReadOnlySubclassingFieldSubtype]
4663 from typing import ReadOnly, TypedDict
4664
4665 class A(TypedDict):
4666 key: ReadOnly[float]
4667 class B(A):
4668 key: int
4669 class C(A):
4670 key: ReadOnly[int]
4671
4672 a: A
4673 reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {'key'=: builtins.float})"
4674 b: B
4675 reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'key': builtins.int})"
4676 c: C
4677 reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'key'=: builtins.int})"
4678 [builtins fixtures/dict.pyi]
4679 [typing fixtures/typing-typeddict.pyi]
4680
4681 [case testTypedDictReadOnlySubclassingFieldSubtypeWithForwardReferenceBases]
4682 from typing import ReadOnly, TypedDict
4683
4684 class X("XB"): pass
4685 class Y("YB"): pass
4686 class Z("ZB"): pass
4687
4688 class A(TypedDict):
4689 key: ReadOnly["X"]
4690 class B(A):
4691 key: "Y" # ok: Y subclasses X via YB
4692 class C(A):
4693 key: "Z" # E: Definition of field "key" incompatible with base class "A"
4694
4695 x: A
4696 y: B
4697 x = y # ok: B is a valid subtype of A
4698
4699 class XB: pass
4700 class YB(X): pass
4701 class ZB: pass
4702 [builtins fixtures/dict.pyi]
4703 [typing fixtures/typing-typeddict.pyi]
4704
4705 [case testTypedDictReadOnlyIllegalSubclassingFieldSupertype]
4706 from typing import ReadOnly, TypedDict
4707
4708 class A(TypedDict):
4709 key: ReadOnly[int]
4710 class B(A):
4711 key: float # E: Definition of field "key" incompatible with base class "A"
4712 class C(A):
4713 key: ReadOnly[float] # E: Definition of field "key" incompatible with base class "A"
4714
4715 a: A
4716 reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {'key'=: builtins.int})"
4717 b: B
4718 reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'key': builtins.float})"
4719 c: C
4720 reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'key'=: builtins.float})"
4721 [builtins fixtures/dict.pyi]
4722 [typing fixtures/typing-typeddict.pyi]
4723
4724 [case testTypedDictReadOnlyMixinFieldSubtype]
4725 from typing import ReadOnly, TypedDict
4726
4727 class A(TypedDict):
4728 key: ReadOnly[float]
4729
4730 class B(TypedDict):
4731 key: ReadOnly[int]
4732
4733 class C(B, A): # Left-most base "wins"
4734 pass
4735
4736 class D(A, B): # E: Incompatible definitions of field "key" in base classes "B" and "A" \
4737 # N: This can be resolved by redeclaring the field "key" with a mutually compatible type
4738 pass
4739
4740 class E(A, B):
4741 key: ReadOnly[int] # ok: explicit redefinition
4742
4743 c: C
4744 reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'key'=: builtins.int})"
4745 d: D
4746 reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'key'=: builtins.float})"
4747 e: E
4748 reveal_type(e) # N: Revealed type is "TypedDict('__main__.E', {'key'=: builtins.int})"
4749
4750 # Verify that subclasses are valid subtypes
4751 a: A
4752 b: B
4753 a = c
4754 b = c
4755 a = e
4756 b = e
4757 [builtins fixtures/dict.pyi]
4758 [typing fixtures/typing-typeddict.pyi]
4759
4760 [case testTypedDictReadOnlySubclassingTotality]
4761 from typing import ReadOnly, TypedDict
4762
4763 class A(TypedDict, total=False):
4764 key: ReadOnly[int]
4765
4766 class B(A):
4767 key: int
4768
4769 a: A
4770 reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {'key'?=: builtins.int})"
4771 b: B
4772 reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'key': builtins.int})"
4773
4774 a = b # ok: B is a valid subtype of A
4775 [builtins fixtures/dict.pyi]
4776 [typing fixtures/typing-typeddict.pyi]
4777
4778 [case testTypedDictReadOnlyIllegalSubclassingTotality]
4779 from typing import ReadOnly, TypedDict
4780
4781 class A(TypedDict):
4782 key: ReadOnly[int]
4783
4784 class B(A, total=False):
4785 key: int # E: Field "key" is required in base class "A"
4786
4787 a: A
4788 reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {'key'=: builtins.int})"
4789 b: B
4790 reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'key'?: builtins.int})"
4791 [builtins fixtures/dict.pyi]
4792 [typing fixtures/typing-typeddict.pyi]
4793
4794 [case testTypedDictReadOnlyMixinTotality]
4795 from typing import ReadOnly, TypedDict
4796
4797 class A(TypedDict, total=True):
4798 key: ReadOnly[int]
4799
4800 class B(TypedDict, total=False):
4801 key: ReadOnly[int]
4802
4803 class C(B, A):
4804 pass
4805 class D(A, B):
4806 pass
4807
4808 c: C
4809 reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'key'=: builtins.int})"
4810 d: D
4811 reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'key'=: builtins.int})"
4812 [builtins fixtures/dict.pyi]
4813 [typing fixtures/typing-typeddict.pyi]
4814
4815 [case testTypedDictReadOnlyMixinWithMutableField]
4816 from typing import ReadOnly, TypedDict
4817
4818 class A(TypedDict):
4819 key: ReadOnly[float]
4820
4821 class B(TypedDict):
4822 key: float
4823
4824 class C(TypedDict):
4825 key: int
4826
4827 class D1(A, B): pass
4828 d1: D1
4829 reveal_type(d1) # N: Revealed type is "TypedDict('__main__.D1', {'key': builtins.float})"
4830 class D2(B, A): pass
4831 d2: D2
4832 reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'key': builtins.float})"
4833 class D3(A, C): pass
4834 d3: D3
4835 reveal_type(d3) # N: Revealed type is "TypedDict('__main__.D3', {'key': builtins.int})"
4836 class D4(C, A): pass
4837 d4: D4
4838 reveal_type(d4) # N: Revealed type is "TypedDict('__main__.D4', {'key': builtins.int})"
4839 class D5(A, B, C): pass # E: Incompatible definitions of field "key" in base classes "C" and "B"
4840 d5: D5
4841 reveal_type(d5) # N: Revealed type is "TypedDict('__main__.D5', {'key': builtins.float})"
4842 class D6(C, B, A): pass # E: Incompatible definitions of field "key" in base classes "B" and "C"
4843 d6: D6
4844 reveal_type(d6) # N: Revealed type is "TypedDict('__main__.D6', {'key': builtins.int})"
4845 [builtins fixtures/dict.pyi]
4846 [typing fixtures/typing-typeddict.pyi]
4847
4848
4849 [case testTypedDictRequiredConsistentWithNotRequiredReadOnly]
4850 from typing import NotRequired, ReadOnly, Required, TypedDict
4851
4852 class A(TypedDict):
4853 x: NotRequired[ReadOnly[str]]
4854
4855 class B(TypedDict):
4856 x: Required[str]
4857
4858 def f(b: B):
4859 a: A = b # ok
4860 [builtins fixtures/dict.pyi]
4861 [typing fixtures/typing-typeddict.pyi]
4862
4863 [case testTypedDictNotRequiredInconsistentWithRequiredReadOnly]
4864 from typing import NotRequired, ReadOnly, Required, TypedDict
4865
4866 class A(TypedDict):
4867 x: Required[ReadOnly[str]]
4868
4869 class B(TypedDict):
4870 x: NotRequired[str]
4871
4872 def f(b: B):
4873 a: A = b # E: Incompatible types in assignment (expression has type "B", variable has type "A")
4874 [builtins fixtures/dict.pyi]
4875 [typing fixtures/typing-typeddict.pyi]
4876
4877 [case testTypedDictReadOnlyCall]
4878 from typing import ReadOnly, TypedDict
4879
4880 TP = TypedDict("TP", {"one": int, "other": ReadOnly[str]})
4881
4882 x: TP
4883 reveal_type(x["one"]) # N: Revealed type is "builtins.int"
4884 reveal_type(x["other"]) # N: Revealed type is "builtins.str"
4885 x["one"] = 1 # ok
4886 x["other"] = "a" # E: ReadOnly TypedDict key "other" TypedDict is mutated
4887 [builtins fixtures/dict.pyi]
4888 [typing fixtures/typing-typeddict.pyi]
4889
4890 [case testTypedDictReadOnlyABCSubtypes]
4891 from typing import ReadOnly, TypedDict, Mapping, Dict, MutableMapping
4892
4893 class TP(TypedDict):
4894 one: int
4895 other: ReadOnly[int]
4896
4897 def accepts_mapping(m: Mapping[str, object]): ...
4898 def accepts_mutable_mapping(mm: MutableMapping[str, object]): ...
4899 def accepts_dict(d: Dict[str, object]): ...
4900
4901 x: TP
4902 accepts_mapping(x)
4903 accepts_mutable_mapping(x) # E: Argument 1 to "accepts_mutable_mapping" has incompatible type "TP"; expected "MutableMapping[str, object]"
4904 accepts_dict(x) # E: Argument 1 to "accepts_dict" has incompatible type "TP"; expected "dict[str, object]"
4905 [builtins fixtures/dict.pyi]
4906 [typing fixtures/typing-typeddict.pyi]
4907
4908 [case testTypedDictReadOnlyAndNotRequired]
4909 from typing import ReadOnly, TypedDict, NotRequired
4910
4911 class TP(TypedDict):
4912 one: ReadOnly[NotRequired[int]]
4913 two: NotRequired[ReadOnly[str]]
4914
4915 x: TP
4916 reveal_type(x) # N: Revealed type is "TypedDict('__main__.TP', {'one'?=: builtins.int, 'two'?=: builtins.str})"
4917 reveal_type(x.get("one")) # N: Revealed type is "builtins.int | None"
4918 reveal_type(x.get("two")) # N: Revealed type is "builtins.str | None"
4919 x["one"] = 1 # E: ReadOnly TypedDict key "one" TypedDict is mutated
4920 x["two"] = "a" # E: ReadOnly TypedDict key "two" TypedDict is mutated
4921 [builtins fixtures/dict.pyi]
4922 [typing fixtures/typing-typeddict.pyi]
4923
4924 [case testMeetOfTypedDictsWithNonOverlappingReadOnlyKeys]
4925 from typing import TypeVar, Callable, TypedDict, ReadOnly
4926 XY = TypedDict('XY', {'x': ReadOnly[int], 'y': int})
4927 YZ = TypedDict('YZ', {'y': int, 'z': ReadOnly[int]})
4928 T = TypeVar('T')
4929 def f(x: Callable[[T, T], None]) -> T: pass
4930 def g(x: XY, y: YZ) -> None: pass
4931 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'=: builtins.int, 'y': builtins.int, 'z'=: builtins.int})"
4932 [builtins fixtures/dict.pyi]
4933 [typing fixtures/typing-typeddict.pyi]
4934
4935 [case testMeetOfTypedDictsWithOverlappingReadOnlyAndMutableKeys]
4936 from typing import TypedDict, TypeVar, Callable, ReadOnly
4937 XY = TypedDict('XY', {'x': int, 'y': int})
4938 YZ = TypedDict('YZ', {'y': ReadOnly[int], 'z': int})
4939 T = TypeVar('T')
4940 def f(x: Callable[[T, T], None]) -> T: pass
4941 def g(x: XY, y: YZ) -> None: pass
4942 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.int, 'z': builtins.int})"
4943 [builtins fixtures/dict.pyi]
4944 [typing fixtures/typing-typeddict.pyi]
4945
4946 [case testMeetOfTypedDictsWithDifferingMutabilityAndAny]
4947 from typing import Any, TypedDict, TypeVar, Callable, ReadOnly
4948 A = TypedDict('A', {'x': Any})
4949 B = TypedDict('B', {'x': ReadOnly[int]})
4950 C = TypedDict('C', {'x': ReadOnly[Any]})
4951 D = TypedDict('D', {'x': int})
4952 T = TypeVar('T')
4953 def f(x: Callable[[T, T], None]) -> T: pass
4954 def gAB(x: A, y: B) -> None: pass
4955 def gBA(x: B, y: A) -> None: pass
4956 def gCD(x: C, y: D) -> None: pass
4957 def gDC(x: D, y: C) -> None: pass
4958 reveal_type(f(gAB)) # N: Revealed type is "TypedDict({'x': builtins.int})"
4959 reveal_type(f(gBA)) # N: Revealed type is "TypedDict({'x': builtins.int})"
4960 reveal_type(f(gCD)) # N: Revealed type is "TypedDict({'x': builtins.int})"
4961 reveal_type(f(gDC)) # N: Revealed type is "TypedDict({'x': builtins.int})"
4962 [builtins fixtures/dict.pyi]
4963 [typing fixtures/typing-typeddict.pyi]
4964
4965 [case testMeetOfTypedDictsWithIncompatibleReadOnlyCommonKeysIsUninhabitedUnlessNotRequired]
4966 from typing import TypedDict, TypeVar, Callable, ReadOnly
4967 A = TypedDict('A', {'x': ReadOnly[int]})
4968 B = TypedDict('B', {'x': ReadOnly[str]})
4969 C = TypedDict('C', {'x': ReadOnly[int]}, total=False)
4970 D = TypedDict('D', {'x': ReadOnly[str]}, total=False)
4971 T = TypeVar('T')
4972 def meet(x: Callable[[T, T], None]) -> T: pass
4973 def fAB(x: A, y: B) -> None: pass
4974 def fAD(x: A, y: D) -> None: pass
4975 def fCB(x: C, y: B) -> None: pass
4976 def fCD(x: C, y: D) -> None: pass
4977 if int():
4978 reveal_type(meet(fAB)) # N: Revealed type is "Never"
4979 if int():
4980 reveal_type(meet(fAD)) # N: Revealed type is "Never"
4981 if int():
4982 reveal_type(meet(fCB)) # N: Revealed type is "Never"
4983 reveal_type(meet(fCD)) # N: Revealed type is "TypedDict({'x'?=: Never})"
4984 [builtins fixtures/dict.pyi]
4985 [typing fixtures/typing-typeddict.pyi]
4986
4987 [case testMeetOfTypedDictsWithCompatibleReadOnlyAndMutableCommonKeys]
4988 from typing import TypedDict, TypeVar, Callable, NotRequired, ReadOnly, Union
4989 A = TypedDict('A', {'x': int, 'y': ReadOnly[Union[int, str]]})
4990 B = TypedDict('B', {'x': ReadOnly[float], 'y': str})
4991 C = TypedDict('C', {'x': ReadOnly[NotRequired[float]], 'y': str})
4992 D = TypedDict('D', {'x': NotRequired[int], 'y': ReadOnly[Union[int, str]]})
4993 T = TypeVar('T')
4994 def meet(x: Callable[[T, T], None]) -> T: pass
4995 def fAB(x: A, y: B) -> None: pass
4996 def fBA(x: B, y: A) -> None: pass
4997 def fAC(x: A, y: C) -> None: pass
4998 def fCA(x: C, y: A) -> None: pass
4999 def fCD(x: C, y: D) -> None: pass
5000 def fDC(x: D, y: C) -> None: pass
5001 reveal_type(meet(fAB)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.str})"
5002 reveal_type(meet(fBA)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.str})"
5003 reveal_type(meet(fAC)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.str})"
5004 reveal_type(meet(fCA)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y': builtins.str})"
5005 reveal_type(meet(fCD)) # N: Revealed type is "TypedDict({'x'?: builtins.int, 'y': builtins.str})"
5006 reveal_type(meet(fDC)) # N: Revealed type is "TypedDict({'x'?: builtins.int, 'y': builtins.str})"
5007 [builtins fixtures/dict.pyi]
5008 [typing fixtures/typing-typeddict.pyi]
5009
5010 [case testMeetOfTypedDictsWithIncompatibleReadOnlyAndMutableCommonKeysIsUninhabited]
5011 from typing import TypedDict, TypeVar, Callable, ReadOnly
5012 XYa = TypedDict('XYa', {'x': int, 'y': ReadOnly[int]})
5013 YbZ = TypedDict('YbZ', {'y': str, 'z': int})
5014 T = TypeVar('T')
5015 def f(x: Callable[[T, T], None]) -> T: pass
5016 def g(x: XYa, y: YbZ) -> None: pass
5017 reveal_type(f(g)) # N: Revealed type is "Never"
5018 [builtins fixtures/dict.pyi]
5019 [typing fixtures/typing-typeddict.pyi]
5020
5021 [case testMeetOfTypedDictsWithCompatibleReadOnlyCommonKeys]
5022 from typing import TypedDict, TypeVar, Callable, ReadOnly
5023 A = TypedDict('A', {'a': int})
5024 B = TypedDict('B', {'b': int})
5025 Xa = TypedDict('Xa', {'x': ReadOnly[A]})
5026 Xb = TypedDict('Xb', {'x': ReadOnly[B]})
5027 T = TypeVar('T')
5028 def f(x: Callable[[T, T], None]) -> T: pass
5029 def g(x: Xa, y: Xb) -> None: pass
5030 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'=: TypedDict({'a': builtins.int, 'b': builtins.int})})"
5031 [builtins fixtures/dict.pyi]
5032 [typing fixtures/typing-typeddict.pyi]
5033
5034 [case testMeetOfTypedDictsWithReadOnlyKeysAndAny]
5035 from typing import Any, TypedDict, TypeVar, Callable, ReadOnly
5036 A = TypedDict('A', {'x': ReadOnly[Any]})
5037 B = TypedDict('B', {'x': ReadOnly[int]})
5038 T = TypeVar('T')
5039 def f(x: Callable[[T, T], None]) -> T: pass
5040 def g(x: A, y: B) -> None: pass
5041 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'=: builtins.int})"
5042 [builtins fixtures/dict.pyi]
5043 [typing fixtures/typing-typeddict.pyi]
5044
5045 [case testMeetOfReadOnlyTypedDictsWithNoCommonKeysHasAllKeysAndNewFallback]
5046 from typing import TypedDict, TypeVar, Callable, ReadOnly
5047 X = TypedDict('X', {'x': ReadOnly[int]})
5048 Z = TypedDict('Z', {'z': ReadOnly[int]})
5049 T = TypeVar('T')
5050 def f(x: Callable[[T, T], None]) -> T: pass
5051 def g(x: X, y: Z) -> None: pass
5052 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'=: builtins.int, 'z'=: builtins.int})"
5053 [builtins fixtures/dict.pyi]
5054 [typing fixtures/typing-typeddict.pyi]
5055
5056 [case testMeetOfReadOnlyTypedDictsWithNonTotal]
5057 from typing import TypedDict, TypeVar, Callable, ReadOnly
5058 XY = TypedDict('XY', {'x': ReadOnly[int], 'y': ReadOnly[int]}, total=False)
5059 YZ = TypedDict('YZ', {'y': ReadOnly[int], 'z': ReadOnly[int]}, total=False)
5060 T = TypeVar('T')
5061 def f(x: Callable[[T, T], None]) -> T: pass
5062 def g(x: XY, y: YZ) -> None: pass
5063 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'?=: builtins.int, 'y'?=: builtins.int, 'z'?=: builtins.int})"
5064 [builtins fixtures/dict.pyi]
5065 [typing fixtures/typing-typeddict.pyi]
5066
5067 [case testMeetOfReadOnlyTypedDictsWithNonOverlappingNonTotalAndTotal]
5068 from typing import TypedDict, TypeVar, Callable, ReadOnly
5069 XY = TypedDict('XY', {'x': ReadOnly[int]}, total=False)
5070 YZ = TypedDict('YZ', {'y': ReadOnly[int], 'z': ReadOnly[int]})
5071 T = TypeVar('T')
5072 def f(x: Callable[[T, T], None]) -> T: pass
5073 def g(x: XY, y: YZ) -> None: pass
5074 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'?=: builtins.int, 'y'=: builtins.int, 'z'=: builtins.int})"
5075 [builtins fixtures/dict.pyi]
5076 [typing fixtures/typing-typeddict.pyi]
5077
5078 [case testMeetOfReadOnlyTypedDictsWithOverlappingNonTotalAndTotal]
5079 from typing import TypedDict, TypeVar, Callable, ReadOnly
5080 XY = TypedDict('XY', {'x': ReadOnly[int], 'y': ReadOnly[int]}, total=False)
5081 YZ = TypedDict('YZ', {'y': ReadOnly[int], 'z': ReadOnly[int]})
5082 T = TypeVar('T')
5083 def f(x: Callable[[T, T], None]) -> T: pass
5084 def g(x: XY, y: YZ) -> None: pass
5085 reveal_type(f(g)) # N: Revealed type is "TypedDict({'x'?=: builtins.int, 'y'=: builtins.int, 'z'=: builtins.int})"
5086 [builtins fixtures/dict.pyi]
5087 [typing fixtures/typing-typeddict.pyi]
5088
5089 [case testTypedDictReadOnlyUnpack]
5090 from typing import TypedDict
5091 from typing_extensions import Unpack, ReadOnly
5092
5093 class TD(TypedDict):
5094 x: ReadOnly[int]
5095 y: str
5096
5097 def func(**kwargs: Unpack[TD]):
5098 kwargs["x"] = 1 # E: ReadOnly TypedDict key "x" TypedDict is mutated
5099 kwargs["y" ] = "a"
5100 [builtins fixtures/dict.pyi]
5101 [typing fixtures/typing-typeddict.pyi]
5102
5103 [case testIncorrectTypedDictSpecialFormsUsage]
5104 from typing import ReadOnly, TypedDict, NotRequired, Required
5105
5106 x: ReadOnly[int] # E: ReadOnly[] can be only used in a TypedDict definition
5107 y: Required[int] # E: Required[] can be only used in a TypedDict definition
5108 z: NotRequired[int] # E: NotRequired[] can be only used in a TypedDict definition
5109
5110 class TP(TypedDict):
5111 a: ReadOnly[ReadOnly[int]] # E: "ReadOnly[]" type cannot be nested
5112 b: ReadOnly[NotRequired[ReadOnly[str]]] # E: "ReadOnly[]" type cannot be nested
5113 c: NotRequired[Required[int]] # E: "Required[]" type cannot be nested
5114 d: Required[NotRequired[int]] # E: "NotRequired[]" type cannot be nested
5115 e: Required[ReadOnly[NotRequired[int]]] # E: "NotRequired[]" type cannot be nested
5116 f: ReadOnly[ReadOnly[ReadOnly[int]]] # E: "ReadOnly[]" type cannot be nested
5117 g: Required[Required[int]] # E: "Required[]" type cannot be nested
5118 h: NotRequired[NotRequired[int]] # E: "NotRequired[]" type cannot be nested
5119
5120 j: NotRequired[ReadOnly[Required[ReadOnly[int]]]] # E: "Required[]" type cannot be nested \
5121 # E: "ReadOnly[]" type cannot be nested
5122
5123 k: ReadOnly # E: "ReadOnly[]" must have exactly one type argument
5124 [builtins fixtures/dict.pyi]
5125 [typing fixtures/typing-typeddict.pyi]
5126
5127 [case testTypedDictAnnotatedWithSpecialForms]
5128 from typing import NotRequired, ReadOnly, Required, TypedDict
5129 from typing_extensions import Annotated
5130
5131 class A(TypedDict):
5132 a: Annotated[NotRequired[ReadOnly[int]], ""] # ok
5133 b: NotRequired[ReadOnly[Annotated[int, ""]]] # ok
5134 [builtins fixtures/dict.pyi]
5135 [typing fixtures/typing-typeddict.pyi]
5136
5137 [case testTypedDictReadOnlyCovariant]
5138 from typing import ReadOnly, TypedDict, Union
5139
5140 class A(TypedDict):
5141 a: ReadOnly[Union[int, str]]
5142
5143 class A2(TypedDict):
5144 a: ReadOnly[int]
5145
5146 class B(TypedDict):
5147 a: int
5148
5149 class B2(TypedDict):
5150 a: Union[int, str]
5151
5152 class B3(TypedDict):
5153 a: int
5154
5155 def fa(a: A) -> None: ...
5156 def fa2(a: A2) -> None: ...
5157
5158 b: B = {"a": 1}
5159 fa(b)
5160 fa2(b)
5161 b2: B2 = {"a": 1}
5162 fa(b2)
5163 fa2(b2) # E: Argument 1 to "fa2" has incompatible type "B2"; expected "A2"
5164
5165 class C(TypedDict):
5166 a: ReadOnly[Union[int, str]]
5167 b: Union[str, bytes]
5168
5169 class D(TypedDict):
5170 a: int
5171 b: str
5172
5173 d: D = {"a": 1, "b": "x"}
5174 c: C = d # E: Incompatible types in assignment (expression has type "D", variable has type "C")
5175 [builtins fixtures/dict.pyi]
5176 [typing fixtures/typing-typeddict.pyi]
5177
5178 [case testTypedDictJoinWithReadOnly]
5179 from typing import ReadOnly, TypedDict, TypeVar
5180 A = TypedDict('A', {'x': ReadOnly[int]})
5181 B = TypedDict('B', {'x': ReadOnly[int]}, total=False)
5182 C = TypedDict('C', {'x': int})
5183 D = TypedDict('D', {'x': int}, total=False)
5184 T = TypeVar('T')
5185 def j(x: T, y: T) -> T: return x
5186 a: A
5187 b: B
5188 c: C
5189 d: D
5190 reveal_type(j(a, b)) # N: Revealed type is "TypedDict({'x'?=: builtins.int})"
5191 reveal_type(j(b, a)) # N: Revealed type is "TypedDict({'x'?=: builtins.int})"
5192 reveal_type(j(a, c)) # N: Revealed type is "TypedDict({'x'=: builtins.int})"
5193 reveal_type(j(c, a)) # N: Revealed type is "TypedDict({'x'=: builtins.int})"
5194 reveal_type(j(a, d)) # N: Revealed type is "TypedDict({'x'?=: builtins.int})"
5195 reveal_type(j(d, a)) # N: Revealed type is "TypedDict({'x'?=: builtins.int})"
5196 reveal_type(j(b, c)) # N: Revealed type is "TypedDict({'x'?=: builtins.int})"
5197 reveal_type(j(c, b)) # N: Revealed type is "TypedDict({'x'?=: builtins.int})"
5198 [builtins fixtures/dict.pyi]
5199 [typing fixtures/typing-typeddict.pyi]
5200
5201
5202 # Closed
5203 # See https://peps.python.org/pep-0728/
5204
5205 [case testTypedDictWithClosedFalse]
5206 from typing import TypedDict
5207 D = TypedDict('D', {'x': int, 'y': str}, closed=False)
5208 d: D
5209 reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.str})"
5210 class E(TypedDict, closed=False):
5211 x: int
5212 y: str
5213 e: E
5214 reveal_type(e) # N: Revealed type is "TypedDict('__main__.E', {'x': builtins.int, 'y': builtins.str})"
5215 [builtins fixtures/dict.pyi]
5216 [typing fixtures/typing-typeddict.pyi]
5217
5218 [case testTypedDictWithClosedTrue]
5219 from typing import TypedDict
5220 D = TypedDict('D', {'x': int, 'y': str}, closed=True)
5221 d: D
5222 reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.str}, closed=True)"
5223 class E(TypedDict, closed=True):
5224 x: int
5225 y: str
5226 e: E
5227 reveal_type(e) # N: Revealed type is "TypedDict('__main__.E', {'x': builtins.int, 'y': builtins.str}, closed=True)"
5228 [builtins fixtures/dict.pyi]
5229 [typing fixtures/typing-typeddict.pyi]
5230
5231 [case testTypedDictWithInvalidClosedArgument]
5232 from typing import TypedDict
5233 A = TypedDict('A', {'x': int}, closed=0) # E: "closed" argument must be a True or False literal
5234 B = TypedDict('B', {'x': int}, closed=bool) # E: "closed" argument must be a True or False literal
5235 class C(TypedDict, closed=0): # E: "closed" argument must be a True or False literal
5236 x: int
5237 class D(TypedDict, closed=bool): # E: "closed" argument must be a True or False literal
5238 x: int
5239 [builtins fixtures/dict.pyi]
5240 [typing fixtures/typing-typeddict.pyi]
5241
5242 [case testTypedDictWithClosedAndTotal]
5243 from typing import TypedDict
5244 A = TypedDict('A', {'x': int, 'y': str}, total=False, closed=True)
5245 B = TypedDict('B', {'x': int, 'y': str}, closed=True, total=False)
5246 C = TypedDict('C', {'x': int, 'y': str}, total=True, closed=False)
5247 a: A
5248 b: B
5249 c: C
5250 reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {'x'?: builtins.int, 'y'?: builtins.str}, closed=True)"
5251 reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'x'?: builtins.int, 'y'?: builtins.str}, closed=True)"
5252 reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'x': builtins.int, 'y': builtins.str})"
5253 [builtins fixtures/dict.pyi]
5254 [typing fixtures/typing-typeddict.pyi]
5255
5256 [case testTypedDictWithDuplicateKeywordArguments_no_parallel]
5257 from typing import TypedDict
5258 A = TypedDict('A', {'x': int}, closed=True, closed=False) # E: Repeated keyword argument "closed" for "TypedDict"
5259 B = TypedDict('B', {'x': int}, total=True, total=False) # E: Repeated keyword argument "total" for "TypedDict"
5260 [builtins fixtures/dict.pyi]
5261 [typing fixtures/typing-typeddict.pyi]
5262
5263 [case testTypedDictSubclassingClosed]
5264 from typing import TypedDict
5265 class D(TypedDict, closed=True):
5266 x: int
5267 y: float
5268 d: D
5269 reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.float}, closed=True)"
5270
5271 class D1(D): pass
5272 d1: D1
5273 reveal_type(d1) # N: Revealed type is "TypedDict('__main__.D1', {'x': builtins.int, 'y': builtins.float}, closed=True)"
5274
5275 class D2(D, closed=True): pass
5276 d2: D2
5277 reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'x': builtins.int, 'y': builtins.float}, closed=True)"
5278
5279 class D3(D, closed=False): pass # E: Open TypedDict class cannot subclass closed TypedDict class "D"
5280 d3: D3
5281 reveal_type(d3) # N: Revealed type is "TypedDict('__main__.D3', {'x': builtins.int, 'y': builtins.float})"
5282
5283 class D4(D):
5284 z: int # E: Cannot extend closed base class "D" with new field "z"
5285 d4: D4
5286 reveal_type(d4) # N: Revealed type is "TypedDict('__main__.D4', {'x': builtins.int, 'y': builtins.float, 'z': builtins.int}, closed=True)"
5287
5288 class D5(D):
5289 x: int
5290 d5: D5
5291 reveal_type(d5) # N: Revealed type is "TypedDict('__main__.D5', {'x': builtins.int, 'y': builtins.float}, closed=True)"
5292
5293 class D6(D):
5294 x: float # E: Definition of field "x" incompatible with base class "D"
5295 y: int # E: Definition of field "y" incompatible with base class "D"
5296 d6: D6
5297 reveal_type(d6) # N: Revealed type is "TypedDict('__main__.D6', {'x': builtins.float, 'y': builtins.int}, closed=True)"
5298
5299 class D7(TypedDict, closed=True):
5300 x: int
5301 z: float
5302 class D8(D7, D): # E: Cannot extend closed base class "D7" with field "y" from base class "D" \
5303 # E: Cannot extend closed base class "D" with field "z" from base class "D7"
5304 pass
5305 d8: D8
5306 reveal_type(d8) # N: Revealed type is "TypedDict('__main__.D8', {'x': builtins.int, 'y': builtins.float, 'z': builtins.float}, closed=True)"
5307 [builtins fixtures/dict.pyi]
5308 [typing fixtures/typing-typeddict.pyi]
5309
5310 [case testTypedDictSubclassingOpenAndClosed]
5311 from typing import TypedDict
5312 class B1(TypedDict, closed=True):
5313 x: int
5314 y: float
5315 class B2(TypedDict):
5316 x: int
5317 class D1(B1, B2): pass
5318 class D2(B2, B1): pass
5319 d1: D1
5320 d2: D2
5321 reveal_type(d1) # N: Revealed type is "TypedDict('__main__.D1', {'x': builtins.int, 'y': builtins.float}, closed=True)"
5322 reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'x': builtins.int, 'y': builtins.float}, closed=True)"
5323 class B3(TypedDict):
5324 z: int
5325 class D3(B1, B3): pass # E: Cannot extend closed base class "B1" with field "z" from base class "B3"
5326 class D4(B3, B1): pass # E: Cannot extend closed base class "B1" with field "z" from base class "B3"
5327 d3: D3
5328 d4: D4
5329 reveal_type(d3) # N: Revealed type is "TypedDict('__main__.D3', {'z': builtins.int, 'x': builtins.int, 'y': builtins.float}, closed=True)"
5330 reveal_type(d4) # N: Revealed type is "TypedDict('__main__.D4', {'x': builtins.int, 'y': builtins.float, 'z': builtins.int}, closed=True)"
5331 [builtins fixtures/dict.pyi]
5332 [typing fixtures/typing-typeddict.pyi]
5333
5334 [case testCanSubclassClosedTypedDictWithForwardDeclarations]
5335 from typing import TypedDict, final
5336
5337 class D1(TypedDict, closed=True):
5338 forward_declared: "ForwardDeclared"
5339
5340 class D2(D1):
5341 pass
5342
5343 class ForwardDeclared: pass
5344
5345 d2: D2
5346 reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'forward_declared': __main__.ForwardDeclared}, closed=True)"
5347
5348 [builtins fixtures/dict.pyi]
5349 [typing fixtures/typing-full.pyi]
5350
5351 [case testTypedDictSubtypingClosedMustRemainClosed]
5352 from typing import TypedDict
5353 A = TypedDict('A', {'x': int}, closed=True)
5354 B = TypedDict('B', {'x': int}, closed=True)
5355 C = TypedDict('C', {'x': int}, closed=False)
5356 D = TypedDict('D', {'x': int}, closed=False)
5357 def f(x: A) -> None: pass
5358 def g(x: C) -> None: pass
5359 a: A
5360 b: B
5361 c: C
5362 d: D
5363 f(b)
5364 f(d) # E: Argument 1 to "f" has incompatible type "D"; expected "A"
5365 g(d)
5366 g(b)
5367 [builtins fixtures/dict.pyi]
5368 [typing fixtures/typing-typeddict.pyi]
5369
5370 [case testTypedDictSubtypingCannotAddKeysToAClosedSupertype]
5371 from typing import TypedDict
5372 A = TypedDict('A', {'x': int}, closed=True)
5373 B = TypedDict('B', {'x': int, 'y': int}, closed=True)
5374 C = TypedDict('C', {'x': int})
5375 D = TypedDict('D', {'x': int, 'y': int})
5376 def f(x: A) -> None: pass
5377 def g(x: C) -> None: pass
5378 b: B
5379 d: D
5380 f(b) # E: Argument 1 to "f" has incompatible type "B"; expected "A"
5381 g(d)
5382 [builtins fixtures/dict.pyi]
5383 [typing fixtures/typing-typeddict.pyi]
5384
5385 [case testTypedDictSubtypingCanDropOptionalReadonlyKeysInAClosedSubtype]
5386 from typing import ReadOnly, TypedDict
5387 # Optional, readonly, closed: permitted
5388 A = TypedDict('A', {'x': int, 'y': ReadOnly[int]}, total=False, closed=True)
5389 B = TypedDict('B', {'x': int}, total=False, closed=True)
5390 b: B
5391 def f_a(x: A) -> None: pass
5392 f_a(b)
5393
5394 # Optional, readonly, open: not permitted
5395 C = TypedDict('C', {'x': int, 'y': ReadOnly[int]}, total=False)
5396 D = TypedDict('D', {'x': int}, total=False)
5397 d: D
5398 def f_c(x: C) -> None: pass
5399 f_c(d) # E: Argument 1 to "f_c" has incompatible type "D"; expected "C"
5400
5401 # Optional, mutable, closed: not permitted
5402 E = TypedDict('E', {'x': int, 'y': int}, total=False, closed=True)
5403 F = TypedDict('F', {'x': int}, total=False, closed=True)
5404 f: F
5405 def f_e(x: E) -> None: pass
5406 f_e(f) # E: Argument 1 to "f_e" has incompatible type "F"; expected "E"
5407
5408 # Required, readonly, closed: not permitted
5409 G = TypedDict('G', {'x': int, 'y': ReadOnly[int]}, closed=True)
5410 H = TypedDict('H', {'x': int}, closed=True)
5411 h: H
5412 def f_g(x: G) -> None: pass
5413 f_g(h) # E: Argument 1 to "f_g" has incompatible type "H"; expected "G"
5414
5415 [builtins fixtures/dict.pyi]
5416 [typing fixtures/typing-typeddict.pyi]
5417
5418 [case testTypedDictSubtypingClosedTypeVarBound]
5419 from typing import TypedDict, TypeVar
5420 A = TypedDict('A', {'x': int}, closed=True)
5421 B = TypedDict('B', {'x': int})
5422 TA = TypeVar('TA', bound=A)
5423 TB = TypeVar('TB', bound=B)
5424 def fA(t: TA) -> TA: return t
5425 def fB(t: TB) -> TB: return t
5426 a: A
5427 b: B
5428 fA(a)
5429 fA(b) # E: Value of type variable "TA" of "fA" cannot be "B"
5430 fB(a)
5431 fB(b)
5432 [builtins fixtures/dict.pyi]
5433 [typing fixtures/typing-typeddict.pyi]
5434
5435 [case testTypedDictSubtypingClosedExplicitNever]
5436 from typing import NotRequired, ReadOnly, TypedDict
5437 from typing_extensions import Never
5438 A = TypedDict('A', {}, closed=True)
5439 B = TypedDict('B', {'x': NotRequired[Never]}, closed=True)
5440 C = TypedDict('C', {'x': ReadOnly[NotRequired[Never]]}, closed=True)
5441 def f_a(x: A) -> None: pass
5442 def f_b(x: B) -> None: pass
5443 def f_c(x: C) -> None: pass
5444 a: A
5445 b: B
5446 c: C
5447 # Logically identical types: legal
5448 f_a(b)
5449 f_b(a)
5450 # Subtype allows key removal: legal
5451 f_c(a)
5452 f_c(b)
5453 # Subtype prevents key removal: illegal
5454 f_a(c) # E: Argument 1 to "f_a" has incompatible type "C"; expected "A"
5455 f_b(c) # E: Argument 1 to "f_b" has incompatible type "C"; expected "B"
5456 [builtins fixtures/dict.pyi]
5457 [typing fixtures/typing-typeddict.pyi]
5458
5459 [case testJoinOfClosedTypedDict]
5460 from typing import Any, TypedDict, TypeVar
5461 A = TypedDict('A', {'x': int}, closed=True)
5462 B = TypedDict('B', {'y': int})
5463 C = TypedDict('C', {'y': int}, closed=True)
5464 D = TypedDict('D', {'x': int, 'y': int}, closed=True)
5465 E = TypedDict('E', {'x': Any, 'y': Any})
5466 T = TypeVar('T')
5467 def j(x: T, y: T) -> T: return x
5468 a: A
5469 b: B
5470 c: C
5471 d: D
5472 e: E
5473 reveal_type(j(a, b)) # N: Revealed type is "TypedDict({'y'?=: builtins.int})"
5474 reveal_type(j(b, a)) # N: Revealed type is "TypedDict({'y'?=: builtins.int})"
5475 reveal_type(j(a, c)) # N: Revealed type is "TypedDict({'x'?=: builtins.int, 'y'?=: builtins.int}, closed=True)"
5476 reveal_type(j(c, a)) # N: Revealed type is "TypedDict({'y'?=: builtins.int, 'x'?=: builtins.int}, closed=True)"
5477 reveal_type(j(a, d)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y'?=: builtins.int}, closed=True)"
5478 reveal_type(j(d, a)) # N: Revealed type is "TypedDict({'x': builtins.int, 'y'?=: builtins.int}, closed=True)"
5479 reveal_type(j(a, e)) # N: Revealed type is "TypedDict({'x': Any, 'y'?=: Any})"
5480 reveal_type(j(e, a)) # N: Revealed type is "TypedDict({'x': Any, 'y'?=: Any})"
5481 reveal_type(j(b, e)) # N: Revealed type is "TypedDict({'y': Any})"
5482 reveal_type(j(e, b)) # N: Revealed type is "TypedDict({'y': Any})"
5483 [builtins fixtures/dict.pyi]
5484 [typing fixtures/typing-typeddict.pyi]
5485
5486 [case testMeetOfClosedTypedDictsWithMatchingRequiredKeysIsNotAnonymous]
5487 from typing import TypedDict, TypeVar, Callable
5488 X = TypedDict('X', {'x': int, 'y': int}, closed=True)
5489 Y = TypedDict('Y', {'x': int, 'y': int}, closed=True)
5490 Z = TypedDict('Z', {'x': int, 'y': int})
5491 T = TypeVar('T')
5492 def meet(x: Callable[[T, T], None]) -> T: pass
5493 def fXY(x: X, y: Y) -> None: pass
5494 def fYX(x: Y, y: X) -> None: pass
5495 def fXZ(x: X, y: Z) -> None: pass
5496 def fZX(x: Z, y: X) -> None: pass
5497 reveal_type(meet(fXY)) # N: Revealed type is "TypedDict('__main__.X', {'x': builtins.int, 'y': builtins.int}, closed=True)"
5498 reveal_type(meet(fYX)) # N: Revealed type is "TypedDict('__main__.Y', {'x': builtins.int, 'y': builtins.int}, closed=True)"
5499 reveal_type(meet(fXZ)) # N: Revealed type is "TypedDict('__main__.X', {'x': builtins.int, 'y': builtins.int}, closed=True)"
5500 reveal_type(meet(fZX)) # N: Revealed type is "TypedDict('__main__.X', {'x': builtins.int, 'y': builtins.int}, closed=True)"
5501 [builtins fixtures/dict.pyi]
5502 [typing fixtures/typing-typeddict.pyi]
5503
5504 [case testMeetOfClosedTypedDictsWithDifferentKeys]
5505 from typing import TypedDict, TypeVar, Callable, ReadOnly
5506 T = TypeVar('T')
5507 def meet(x: Callable[[T, T], None]) -> T: pass
5508 A = TypedDict('A', {'a': int}, closed=True)
5509 B = TypedDict('B', {'b': int}, closed=True)
5510 def fAB(x: A, y: B) -> None: pass
5511 if int():
5512 reveal_type(meet(fAB)) # N: Revealed type is "Never"
5513 C = TypedDict('C', {'c': int}, closed=True, total=False)
5514 D = TypedDict('D', {'d': int}, closed=True, total=False)
5515 def fCD(x: C, y: D) -> None: pass
5516 if int():
5517 reveal_type(meet(fCD)) # N: Revealed type is "Never"
5518 E = TypedDict('E', {'e': ReadOnly[int]}, closed=True)
5519 F = TypedDict('F', {'f': ReadOnly[int]}, closed=True)
5520 def fEF(x: E, y: F) -> None: pass
5521 if int():
5522 reveal_type(meet(fEF)) # N: Revealed type is "Never"
5523 G = TypedDict('G', {'g': ReadOnly[int]}, closed=True, total=False)
5524 H = TypedDict('H', {'h': ReadOnly[int]}, closed=True, total=False)
5525 def fAH(x: A, y: H) -> None: pass
5526 if int():
5527 reveal_type(meet(fAH)) # N: Revealed type is "Never"
5528 def fCH(x: C, y: H) -> None: pass
5529 if int():
5530 reveal_type(meet(fCH)) # N: Revealed type is "Never"
5531 def fEH(x: E, y: H) -> None: pass
5532 if int():
5533 reveal_type(meet(fEH)) # N: Revealed type is "Never"
5534 def fGH(x: G, y: H) -> None: pass
5535 if int():
5536 reveal_type(meet(fGH)) # N: Revealed type is "TypedDict({}, closed=True)"
5537 [builtins fixtures/dict.pyi]
5538 [typing fixtures/typing-typeddict.pyi]
5539
5540 [case testMeetOfTypedDictsExplicitAndImplicitClosedMissing]
5541 from typing import Any, NotRequired, ReadOnly, TypedDict, TypeVar, Callable
5542 from typing_extensions import Never
5543 A = TypedDict('A', {'x': ReadOnly[NotRequired[Never]]}, closed=True)
5544 B = TypedDict('B', {'y': ReadOnly[NotRequired[Never]]}, closed=True)
5545 T = TypeVar('T')
5546 def f(x: Callable[[T, T], None]) -> T: pass
5547 def g(x: A, y: B) -> None: pass
5548 reveal_type(f(g)) # N: Revealed type is "TypedDict({}, closed=True)"
5549 [builtins fixtures/dict.pyi]
5550 [typing fixtures/typing-typeddict.pyi]
5551
5552 [case testMeetOfTypedDictClosedMissingAndAny]
5553 from typing import Any, TypedDict, TypeVar, Callable, ReadOnly
5554 T = TypeVar('T')
5555 def meet(x: Callable[[T, T], None]) -> T: pass
5556 A = TypedDict('A', {}, closed=True)
5557 B = TypedDict('B', {'x': Any})
5558 C = TypedDict('C', {'x': Any}, total=False)
5559 def fAB(x: A, y: B) -> None: pass
5560 def fBA(x: B, y: A) -> None: pass
5561 def fAC(x: A, y: C) -> None: pass
5562 def fCA(x: C, y: A) -> None: pass
5563 if int():
5564 reveal_type(meet(fAB)) # N: Revealed type is "Never"
5565 if int():
5566 reveal_type(meet(fBA)) # N: Revealed type is "Never"
5567 reveal_type(meet(fAC)) # N: Revealed type is "TypedDict({}, closed=True)"
5568 reveal_type(meet(fCA)) # N: Revealed type is "TypedDict({}, closed=True)"
5569 [builtins fixtures/dict.pyi]
5570 [typing fixtures/typing-typeddict.pyi]
5571
5572 [case testMeetOfTypedDictsClosedNotRequiredNeverAndAny]
5573 from typing import Any, NotRequired, TypedDict, TypeVar, Callable
5574 from typing_extensions import Never
5575 A = TypedDict('A', {'x': NotRequired[Any], 'y': NotRequired[Never]}, closed=True)
5576 B = TypedDict('B', {'x': NotRequired[Never], 'y': NotRequired[Any]}, closed=True)
5577 T = TypeVar('T')
5578 def f(x: Callable[[T, T], None]) -> T: pass
5579 def g(x: A, y: B) -> None: pass
5580 reveal_type(f(g)) # N: Revealed type is "TypedDict({}, closed=True)"
5581 [builtins fixtures/dict.pyi]
5582 [typing fixtures/typing-typeddict.pyi]
5583
5584 [case testMeetOfOpenAndClosedTypedDictsExtraKeyInClosed]
5585 from typing import TypedDict, TypeVar, Callable, ReadOnly
5586 T = TypeVar('T')
5587 def meet(x: Callable[[T, T], None]) -> T: pass
5588 Ax = TypedDict('Ax', {'a': ReadOnly[float]})
5589 AyB = TypedDict('AyB', {'a': ReadOnly[int], 'b': int}, closed=True)
5590 def fAxAyB(x: Ax, y: AyB) -> None: pass
5591 def fAyBAx(x: AyB, y: Ax) -> None: pass
5592 reveal_type(meet(fAxAyB)) # N: Revealed type is "TypedDict({'a'=: builtins.int, 'b': builtins.int}, closed=True)"
5593 reveal_type(meet(fAyBAx)) # N: Revealed type is "TypedDict({'a'=: builtins.int, 'b': builtins.int}, closed=True)"
5594 [builtins fixtures/dict.pyi]
5595 [typing fixtures/typing-typeddict.pyi]
5596
5597 [case testMeetOfOpenAndClosedTypedDictsExtraKeyInOpen]
5598 from typing import TypedDict, TypeVar, Callable, ReadOnly
5599 T = TypeVar('T')
5600 def meet(x: Callable[[T, T], None]) -> T: pass
5601 C = TypedDict('C', {'a': ReadOnly[float]}, closed=True)
5602 D1 = TypedDict('D1', {'a': ReadOnly[int], 'b': int})
5603 D2 = TypedDict('D2', {'a': ReadOnly[int], 'b': ReadOnly[int]})
5604 D3 = TypedDict('D3', {'a': ReadOnly[int], 'b': int}, total=False)
5605 D4 = TypedDict('D4', {'a': ReadOnly[int], 'b': ReadOnly[int]}, total=False)
5606 def fCD1(x: C, y: D1) -> None: pass
5607 def fD1C(x: D1, y: C) -> None: pass
5608 def fCD2(x: C, y: D2) -> None: pass
5609 def fD2C(x: D2, y: C) -> None: pass
5610 def fCD3(x: C, y: D3) -> None: pass
5611 def fD3C(x: D3, y: C) -> None: pass
5612 def fCD4(x: C, y: D4) -> None: pass
5613 def fD4C(x: D4, y: C) -> None: pass
5614 if int():
5615 reveal_type(meet(fCD1)) # N: Revealed type is "Never"
5616 if int():
5617 reveal_type(meet(fD1C)) # N: Revealed type is "Never"
5618 if int():
5619 reveal_type(meet(fCD2)) # N: Revealed type is "Never"
5620 if int():
5621 reveal_type(meet(fD2C)) # N: Revealed type is "Never"
5622 if int():
5623 reveal_type(meet(fCD3)) # N: Revealed type is "Never"
5624 if int():
5625 reveal_type(meet(fD3C)) # N: Revealed type is "Never"
5626 reveal_type(meet(fCD4)) # N: Revealed type is "TypedDict({'a'=: builtins.int}, closed=True)"
5627 reveal_type(meet(fD4C)) # N: Revealed type is "TypedDict({'a'=: builtins.int}, closed=True)"
5628 [builtins fixtures/dict.pyi]
5629 [typing fixtures/typing-typeddict.pyi]
5630
5631 [case testTypedDictGetMethodClosed]
5632 from typing import TypedDict, Literal
5633 class Unrelated: pass
5634 D = TypedDict('D', {'x': int, 'y': str}, closed=True)
5635 d: D
5636 u: Unrelated
5637 x: Literal['x']
5638 y: Literal['y']
5639 z: Literal['z']
5640 x_or_y: Literal['x', 'y']
5641 x_or_z: Literal['x', 'z']
5642 x_or_y_or_z: Literal['x', 'y', 'z']
5643
5644 # test with literal expression
5645 reveal_type(d.get('x')) # N: Revealed type is "builtins.int"
5646 reveal_type(d.get('y')) # N: Revealed type is "builtins.str"
5647 reveal_type(d.get('z')) # N: Revealed type is "None"
5648 reveal_type(d.get('z', u)) # N: Revealed type is "__main__.Unrelated"
5649
5650 # test with literal type / union of literal types with implicit default
5651 reveal_type(d.get(x)) # N: Revealed type is "builtins.int"
5652 reveal_type(d.get(y)) # N: Revealed type is "builtins.str"
5653 reveal_type(d.get(z)) # N: Revealed type is "None"
5654 reveal_type(d.get(x_or_y)) # N: Revealed type is "builtins.int | builtins.str"
5655 reveal_type(d.get(x_or_z)) # N: Revealed type is "builtins.int | None"
5656 reveal_type(d.get(x_or_y_or_z)) # N: Revealed type is "builtins.int | builtins.str | None"
5657
5658 # test with literal type / union of literal types with explicit default
5659 reveal_type(d.get(x, u)) # N: Revealed type is "builtins.int"
5660 reveal_type(d.get(y, u)) # N: Revealed type is "builtins.str"
5661 reveal_type(d.get(z, u)) # N: Revealed type is "__main__.Unrelated"
5662 reveal_type(d.get(x_or_y, u)) # N: Revealed type is "builtins.int | builtins.str"
5663 reveal_type(d.get(x_or_z, u)) # N: Revealed type is "builtins.int | __main__.Unrelated"
5664 reveal_type(d.get(x_or_y_or_z, u)) # N: Revealed type is "builtins.int | builtins.str | __main__.Unrelated"
5665 [builtins fixtures/dict.pyi]
5666 [typing fixtures/typing-typeddict.pyi]
5667
5668 [case testOperatorContainsNarrowsTypedDicts_unionWithList_closed]
5669 from __future__ import annotations
5670 from typing import assert_type, TypedDict, Union
5671
5672 class D(TypedDict, closed=True):
5673 foo: int
5674
5675 d_or_list: D | list[str]
5676
5677 if 'foo' in d_or_list:
5678 assert_type(d_or_list, Union[D, list[str]])
5679 elif 'bar' in d_or_list:
5680 assert_type(d_or_list, list[str])
5681 else:
5682 assert_type(d_or_list, list[str])
5683
5684 [builtins fixtures/dict.pyi]
5685 [typing fixtures/typing-full.pyi]
5686
5687 [case testOperatorContainsNarrowsTypedDicts_total_closed]
5688 from __future__ import annotations
5689 from typing import assert_type, Literal, TypedDict, TypeVar, Union
5690
5691 class D1(TypedDict, closed=True):
5692 foo: int
5693
5694 class D2(TypedDict, closed=True):
5695 bar: int
5696
5697 d: D1 | D2
5698
5699 if 'foo' in d:
5700 assert_type(d, D1)
5701 else:
5702 assert_type(d, D2)
5703
5704 foo_or_bar: Literal['foo', 'bar']
5705 if foo_or_bar in d:
5706 assert_type(d, Union[D1, D2])
5707 else:
5708 assert_type(d, Union[D1, D2])
5709
5710 foo_or_invalid: Literal['foo', 'invalid']
5711 if foo_or_invalid in d:
5712 assert_type(d, D1)
5713 # won't narrow 'foo_or_invalid'
5714 assert_type(foo_or_invalid, Literal['foo', 'invalid'])
5715 else:
5716 assert_type(d, Union[D1, D2])
5717 # won't narrow 'foo_or_invalid'
5718 assert_type(foo_or_invalid, Literal['foo', 'invalid'])
5719
5720 TD = TypeVar('TD', D1, D2)
5721
5722 def f(arg: TD) -> None:
5723 value: int
5724 if 'foo' in arg:
5725 assert_type(arg['foo'], int)
5726 else:
5727 assert_type(arg['bar'], int)
5728 [builtins fixtures/dict.pyi]
5729 [typing fixtures/typing-full.pyi]
5730
5731 [case testOperatorContainsNarrowsTypedDicts_closed]
5732 # flags: --warn-unreachable
5733 from __future__ import annotations
5734 from typing import assert_type, TypedDict, Union
5735
5736 class DClosed(TypedDict, closed=True):
5737 foo: int
5738
5739 class DNotClosed(TypedDict):
5740 bar: int
5741
5742 d_not_closed: DNotClosed
5743
5744 if 'bar' in d_not_closed:
5745 assert_type(d_not_closed, DNotClosed)
5746 else:
5747 spam = 'ham' # E: Statement is unreachable
5748
5749 if 'spam' in d_not_closed:
5750 assert_type(d_not_closed, DNotClosed)
5751 else:
5752 assert_type(d_not_closed, DNotClosed)
5753
5754 d_closed: DClosed
5755
5756 if 'spam' in d_closed:
5757 spam = 'ham' # E: Statement is unreachable
5758 else:
5759 assert_type(d_closed, DClosed)
5760
5761 d_union: DClosed | DNotClosed
5762
5763 if 'foo' in d_union:
5764 assert_type(d_union, Union[DClosed, DNotClosed])
5765 else:
5766 assert_type(d_union, DNotClosed)
5767 [builtins fixtures/dict.pyi]
5768 [typing fixtures/typing-full.pyi]
5769
5770 [case testOperatorContainsNarrowsTypedDicts_partialThroughTotalFalse_closed]
5771 from __future__ import annotations
5772 from typing import assert_type, Literal, TypedDict, Union
5773
5774 class DTotal(TypedDict, closed=True):
5775 required_key: int
5776
5777 class DNotTotal(TypedDict, total=False, closed=True):
5778 optional_key: int
5779
5780 d: DTotal | DNotTotal
5781
5782 if 'required_key' in d:
5783 assert_type(d, DTotal)
5784 else:
5785 assert_type(d, DNotTotal)
5786
5787 if 'optional_key' in d:
5788 assert_type(d, DNotTotal)
5789 else:
5790 assert_type(d, Union[DTotal, DNotTotal])
5791
5792 key: Literal['optional_key', 'required_key']
5793 if key in d:
5794 assert_type(d, Union[DTotal, DNotTotal])
5795 else:
5796 assert_type(d, Union[DTotal, DNotTotal])
5797 [builtins fixtures/dict.pyi]
5798 [typing fixtures/typing-full.pyi]
5799
5800 [case testOperatorContainsNarrowsTypedDicts_partialThroughNotRequired_closed]
5801 from __future__ import annotations
5802 from typing import assert_type, TypedDict, Union
5803 from typing_extensions import Required, NotRequired
5804
5805 class D1(TypedDict, closed=True):
5806 required_key: Required[int]
5807 optional_key: NotRequired[int]
5808
5809 class D2(TypedDict, closed=True):
5810 abc: int
5811 xyz: int
5812
5813 d: D1 | D2
5814
5815 if 'required_key' in d:
5816 assert_type(d, D1)
5817 else:
5818 assert_type(d, D2)
5819
5820 if 'optional_key' in d:
5821 assert_type(d, D1)
5822 else:
5823 assert_type(d, Union[D1, D2])
5824 [builtins fixtures/dict.pyi]
5825 [typing fixtures/typing-full.pyi]
5826
5827 [case testOperatorContainsNarrowsTypeVarWithClosedTypedDictBound]
5828 from typing import TypedDict, TypeVar
5829 from typing_extensions import Never, assert_type
5830
5831 T = TypeVar('T', bound='D')
5832
5833 class D(TypedDict, closed=True):
5834 a: int
5835
5836 def func(t: T):
5837 if "b" in t:
5838 assert_type(t, Never)
5839 [builtins fixtures/dict.pyi]
5840 [typing fixtures/typing-typeddict.pyi]
5841
5842 [case testTypedDictUnpackFromClosedMissingKey]
5843 # flags: --extra-checks
5844 from typing import TypedDict
5845 from typing_extensions import Never, NotRequired
5846 D1 = TypedDict("D1", {"a": int, "b": str}, closed=True)
5847 D2 = TypedDict("D2", {"a": int, "b": str, "c": int})
5848 D3 = TypedDict("D3", {"a": int, "b": str, "c": NotRequired[int]})
5849 d1: D1
5850 d2: D2 = {**d1} # E: Missing key "c" for TypedDict "D2"
5851 d3: D3 = {**d1}
5852 [builtins fixtures/dict.pyi]
5853 [typing fixtures/typing-typeddict.pyi]
5854
5855 [case testTypedDictUnpackIntoClosed]
5856 # flags: --extra-checks
5857 from typing import Any, Mapping, TypedDict, Union
5858 from typing_extensions import Never, NotRequired
5859 D1 = TypedDict("D1", {"a": int, "b": str}, closed=True)
5860 D2 = TypedDict("D2", {"a": int, "b": str})
5861 D3 = TypedDict("D3", {"c": int, "d": str}, closed=True)
5862 D4 = TypedDict("D4", {"c": int, "d": str})
5863 D5 = TypedDict("D5", {"a": int, "b": str, "c": int, "d": str}, closed=True)
5864 d1: D1
5865 d2: D2
5866 d3: D3
5867 d4: D4
5868 d5: D5
5869 m: Mapping[Any, Any]
5870 u34: Union[D3, D4]
5871 u35: Union[D3, D5]
5872 u5m: Union[D5, Mapping[Any, Any]]
5873 d5 = {**d1, **d3}
5874 d5 = {
5875 **d1,
5876 **d4, # E: Cannot unpack item that may contain extra keys into a closed TypedDict
5877 }
5878 d5 = {
5879 **d2, # E: Cannot unpack item that may contain extra keys into a closed TypedDict
5880 **d3,
5881 }
5882 d5 = {
5883 **d1,
5884 **u34, # E: Cannot unpack item that may contain extra keys into a closed TypedDict
5885 }
5886 d5 = {**d1, **u35}
5887 d5 = {
5888 **m, # E: Cannot unpack item that may contain extra keys into a closed TypedDict
5889 **d5,
5890 }
5891 d5 = {
5892 **u5m, # E: Cannot unpack item that may contain extra keys into a closed TypedDict
5893 }
5894 [builtins fixtures/dict.pyi]
5895 [typing fixtures/typing-typeddict.pyi]
5896
5897
5898 [case testTypedDictFinalAndClassVar]
5899 from typing import TypedDict, Final, ClassVar
5900
5901 class My(TypedDict):
5902 a: Final # E: Final[...] can't be used inside a TypedDict
5903 b: Final[int] # E: Final[...] can't be used inside a TypedDict
5904 c: ClassVar # E: ClassVar[...] can't be used inside a TypedDict
5905 d: ClassVar[int] # E: ClassVar[...] can't be used inside a TypedDict
5906
5907 Func = TypedDict('Func', {
5908 'a': Final, # E: Final[...] can't be used inside a TypedDict
5909 'b': Final[int], # E: Final[...] can't be used inside a TypedDict
5910 'c': ClassVar, # E: ClassVar[...] can't be used inside a TypedDict
5911 'd': ClassVar[int], # E: ClassVar[...] can't be used inside a TypedDict
5912 })
5913 [builtins fixtures/dict.pyi]
5914 [typing fixtures/typing-typeddict.pyi]
5915
5916 [case testTypedDictNestedInClassAndInherited]
5917 from typing import TypedDict
5918
5919 class Base:
5920 class Params(TypedDict):
5921 name: str
5922
5923 class Derived(Base):
5924 pass
5925
5926 class DerivedOverride(Base):
5927 class Params(Base.Params):
5928 pass
5929
5930 Base.Params(name="Robert")
5931 Derived.Params(name="Robert")
5932 DerivedOverride.Params(name="Robert")
5933 [builtins fixtures/dict.pyi]
5934 [typing fixtures/typing-typeddict.pyi]
5935
5936 [case testEnumAsClassMemberNoCrash]
5937 # https://github.com/python/mypy/issues/18736
5938 from typing import TypedDict
5939
5940 class Base:
5941 def __init__(self, namespace: dict[str, str]) -> None:
5942 # Not a bug: trigger defer
5943 names = {n: n for n in namespace if fail} # E: Name "fail" is not defined
5944 self.d = TypedDict("d", names) # E: TypedDict type as attribute is not supported \
5945 # E: TypedDict() expects a dictionary literal as the second argument
5946 [builtins fixtures/dict.pyi]
5947 [typing fixtures/typing-typeddict.pyi]
5948
5949 [case testTypedDictAlias]
5950 from typing import NotRequired, TypedDict
5951 from typing_extensions import TypeAlias
5952
5953 class Base(TypedDict):
5954 foo: int
5955
5956 Base1 = Base
5957 class Child1(Base1):
5958 bar: NotRequired[int]
5959 c11: Child1 = {"foo": 0}
5960 c12: Child1 = {"foo": 0, "bar": 1}
5961 c13: Child1 = {"foo": 0, "bar": 1, "baz": "error"} # E: Extra key "baz" for TypedDict "Child1"
5962
5963 Base2: TypeAlias = Base
5964 class Child2(Base2):
5965 bar: NotRequired[int]
5966 c21: Child2 = {"foo": 0}
5967 c22: Child2 = {"foo": 0, "bar": 1}
5968 c23: Child2 = {"foo": 0, "bar": 1, "baz": "error"} # E: Extra key "baz" for TypedDict "Child2"
5969 [builtins fixtures/dict.pyi]
5970 [typing fixtures/typing-typeddict.pyi]
5971
5972 [case testTypedDictAliasInheritance]
5973 from typing import TypedDict
5974 from typing_extensions import TypeAlias
5975
5976 class A(TypedDict):
5977 x: str
5978 class B(TypedDict):
5979 y: int
5980
5981 B1 = B
5982 B2: TypeAlias = B
5983
5984 class C(A, B1):
5985 pass
5986 c1: C = {"y": 1} # E: Missing key "x" for TypedDict "C"
5987 c2: C = {"x": "x", "y": 2}
5988 c3: C = {"x": 1, "y": 2} # E: Incompatible types (expression has type "int", TypedDict item "x" has type "str")
5989
5990 class D(A, B2):
5991 pass
5992 d1: D = {"y": 1} # E: Missing key "x" for TypedDict "D"
5993 d2: D = {"x": "x", "y": 2}
5994 d3: D = {"x": 1, "y": 2} # E: Incompatible types (expression has type "int", TypedDict item "x" has type "str")
5995 [builtins fixtures/dict.pyi]
5996 [typing fixtures/typing-typeddict.pyi]
5997
5998 [case testTypedDictAliasDuplicateBases]
5999 from typing import TypedDict
6000 from typing_extensions import TypeAlias
6001
6002 class A(TypedDict):
6003 x: str
6004
6005 A1 = A
6006 A2 = A
6007 A3: TypeAlias = A
6008
6009 class E(A1, A2): pass # E: Duplicate base class "A"
6010 class F(A1, A3): pass # E: Duplicate base class "A"
6011 class G(A, A1): pass # E: Duplicate base class "A"
6012
6013 class H(A, list): pass # E: All bases of a new TypedDict must be TypedDict types
6014 [builtins fixtures/dict.pyi]
6015 [typing fixtures/typing-typeddict.pyi]
6016
6017 [case testTypedDictAliasGeneric]
6018 from typing import Generic, TypedDict, TypeVar
6019 from typing_extensions import TypeAlias
6020
6021 _T = TypeVar("_T")
6022
6023 class A(Generic[_T], TypedDict):
6024 x: _T
6025
6026 # This is by design - no_args aliases are only supported for instances
6027 A0 = A
6028 class B(A0[str]): # E: Bad number of arguments for type alias, expected 0, given 1
6029 y: int
6030
6031 A1 = A[_T]
6032 A2: TypeAlias = A[_T]
6033 Aint = A[int]
6034
6035 class C(A1[_T]):
6036 y: str
6037 c1: C[int] = {"x": 0, "y": "a"}
6038 c2: C[int] = {"x": "no", "y": "a"} # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
6039
6040 class D(A2[_T]):
6041 y: str
6042 d1: D[int] = {"x": 0, "y": "a"}
6043 d2: D[int] = {"x": "no", "y": "a"} # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
6044
6045 class E(Aint):
6046 y: str
6047 e1: E = {"x": 0, "y": "a"}
6048 e2: E = {"x": "no", "y": "a"}
6049 [builtins fixtures/dict.pyi]
6050 [typing fixtures/typing-typeddict.pyi]
6051
6052 [case testTypedDictAliasAsInstanceAttribute]
6053 from typing import TypedDict
6054
6055 class Dicts:
6056 class TF(TypedDict, total=False):
6057 user_id: int
6058 TotalFalse = TF
6059
6060 dicts = Dicts()
6061 reveal_type(dicts.TF) # N: Revealed type is "def (*, user_id: builtins.int =) -> TypedDict('__main__.Dicts.TF', {'user_id'?: builtins.int})"
6062 reveal_type(dicts.TotalFalse) # N: Revealed type is "def (*, user_id: builtins.int =) -> TypedDict('__main__.Dicts.TF', {'user_id'?: builtins.int})"
6063 [builtins fixtures/dict.pyi]
6064 [typing fixtures/typing-typeddict.pyi]
6065
6066 [case testRecursiveNestedTypedDictInference]
6067 from typing import TypedDict, Sequence
6068 from typing_extensions import NotRequired
6069
6070 class Component(TypedDict):
6071 type: str
6072 components: NotRequired[Sequence['Component']]
6073
6074 inputs: Sequence[Component] = [{
6075 'type': 'tuple',
6076 'components': [
6077 {'type': 'uint256'},
6078 {'type': 'address'},
6079 ]
6080 }]
6081 [builtins fixtures/dict.pyi]
6082 [typing fixtures/typing-typeddict.pyi]
6083
6084 [case testTypedDictAssignableToWiderContext]
6085 from typing import TypedDict, Union
6086
6087 class TD(TypedDict):
6088 x: int
6089
6090 x: Union[TD, dict[str, str]] = {"x": "foo"}
6091 y: Union[TD, dict[str, int]] = {"x": "foo"} # E: Dict entry 0 has incompatible type "str": "str"; expected "str": "int"
6092
6093 def ok(d: Union[TD, dict[str, str]]) -> None: ...
6094 ok({"x": "foo"})
6095
6096 def bad(d: Union[TD, dict[str, int]]) -> None: ...
6097 bad({"x": "foo"}) # E: Dict entry 0 has incompatible type "str": "str"; expected "str": "int"
6098
6099 [builtins fixtures/dict.pyi]
6100 [typing fixtures/typing-typeddict.pyi]
6101
6102 [case testTypedDictUnpackImportCycle]
6103 import mre
6104
6105 [file mre.py]
6106 from mre_pkg.model import Callback
6107 Callback(callback=1) # E: Argument "callback" to "Callback" has incompatible type "int"; expected "Callback"
6108
6109 [file mre_pkg/model.pyi]
6110 from typing_extensions import Unpack, TYPE_CHECKING, TypedDict
6111 from .callbacks import Callback as Callback
6112
6113 class _ModelInit(TypedDict, total=False):
6114 callback: Callback
6115
6116 class Model:
6117 def __init__(self, **kwargs: Unpack[_ModelInit]) -> None: ...
6118
6119 [file mre_pkg/callbacks.pyi]
6120 from typing_extensions import Unpack, TYPE_CHECKING, TypedDict
6121 from .model import Model, _ModelInit
6122
6123 class _CallbackInit(_ModelInit, total=False): ...
6124
6125 class Callback(Model):
6126 def __init__(self, **kwargs: Unpack[_CallbackInit]) -> None: ...
6127 [builtins fixtures/dict.pyi]
6128 [typing fixtures/typing-typeddict.pyi]