Skip to content

Commit fd7ffbd

Browse files
committed
[docs] Add example of using @final with TypedDict
Fixes python#18543 This is a useful but also non-obvious pattern that seems worthy of a docs example :)
1 parent 42e005c commit fd7ffbd

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

docs/source/typed_dict.rst

+26
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,32 @@ need to give each TypedDict the same key where each value has a unique
289289
:ref:`Literal type <literal_types>`. Then, check that key to distinguish
290290
between your TypedDicts.
291291

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+
292318
Inline TypedDict types
293319
----------------------
294320

0 commit comments

Comments
 (0)