[3.12] Enhance TypedDict docs around required/optional keys (GH-109547) (#109982)

Enhance TypedDict docs around required/optional keys (GH-109547)

As discussed in comments to GH-109544, the semantics of this attribute
are somewhat confusing. Add a note explaining its limitations and
steering users towards __required_keys__ and __optional_keys__ instead.
(cherry picked from commit f49958c886)

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
This commit is contained in:
Miss Islington (bot) 2023-10-04 04:56:58 -07:00 committed by GitHub
parent bbce8bd05d
commit ee2f2bdb30
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -2392,6 +2392,13 @@ types.
>>> Point3D.__total__
True
This attribute reflects *only* the value of the ``total`` argument
to the current ``TypedDict`` class, not whether the class is semantically
total. For example, a ``TypedDict`` with ``__total__`` set to True may
have keys marked with :data:`NotRequired`, or it may inherit from another
``TypedDict`` with ``total=False``. Therefore, it is generally better to use
:attr:`__required_keys__` and :attr:`__optional_keys__` for introspection.
.. attribute:: __required_keys__
.. versionadded:: 3.9
@ -2427,6 +2434,14 @@ types.
.. versionadded:: 3.9
.. note::
If ``from __future__ import annotations`` is used or if annotations
are given as strings, annotations are not evaluated when the
``TypedDict`` is defined. Therefore, the runtime introspection that
``__required_keys__`` and ``__optional_keys__`` rely on may not work
properly, and the values of the attributes may be incorrect.
See :pep:`589` for more examples and detailed rules of using ``TypedDict``.
.. versionadded:: 3.8