File tree 1 file changed +26
-0
lines changed
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change @@ -289,6 +289,32 @@ need to give each TypedDict the same key where each value has a unique
289
289
:ref: `Literal type <literal_types >`. Then, check that key to distinguish
290
290
between your TypedDicts.
291
291
292
+ You can also use :py:class: `@final <https://docs.python.org/3/library/typing.html#typing.final> ` to indicate that an
293
+ instance of TypedDict will not be reassigned or subclassed. This allows mypy to do type refinement based on unique
294
+ properties of the TypedDict:
295
+
296
+ .. code-block :: python
297
+
298
+ from typing import TypedDict, final
299
+
300
+ @final
301
+ class Movie (TypedDict ):
302
+ director: str
303
+ runtime: int
304
+
305
+ @final
306
+ class Book (TypedDict ):
307
+ author: str
308
+ pages: int
309
+
310
+ def foo (movie_or_book : Movie | Book) -> None :
311
+ if ' director' in movie_or_book:
312
+ director = movie_or_book[' director' ]
313
+ runtime = movie_or_book[' runtime' ]
314
+ elif ' author' in movie_or_book:
315
+ author = movie_or_book[' author' ]
316
+ pages = movie_or_book[' pages' ]
317
+
292
318
Inline TypedDict types
293
319
----------------------
294
320
You can’t perform that action at this time.
0 commit comments