Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[docs] Add example of using @final with TypedDict #18547

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/source/typed_dict.rst
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,32 @@ need to give each TypedDict the same key where each value has a unique
:ref:`Literal type <literal_types>`. Then, check that key to distinguish
between your TypedDicts.

You can also use ``@final`` to indicate that the TypedDict definition will not be
subclassed. This allows mypy to do type refinement based on unique properties of
the TypedDict:

.. code-block:: python

from typing import TypedDict, final

@final
class Movie(TypedDict):
director: str
runtime: int

@final
class Book(TypedDict):
author: str
pages: int

def foo(movie_or_book: Movie | Book) -> None:
if 'director' in movie_or_book:
director = movie_or_book['director']
runtime = movie_or_book['runtime']
elif 'author' in movie_or_book:
author = movie_or_book['author']
pages = movie_or_book['pages']

Inline TypedDict types
----------------------

Expand Down