From: Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> Date: Wed, 27 Sep 2023 17:54:27 +0000 (-0700) Subject: [3.11] Enhance TypedDict docs around required/optional keys (GH-109547) (#109983) X-Git-Tag: v3.11.6~30 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=38526a29ed1f45fdc4a4b2f373f63376c4069f1a;p=thirdparty%2FPython%2Fcpython.git [3.11] Enhance TypedDict docs around required/optional keys (GH-109547) (#109983) 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 f49958c886a2f2608f1008186d588efc2a98b445) Co-authored-by: Jelle Zijlstra --- diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index 79f3abd865f6..57384b05fe23 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -2131,6 +2131,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 @@ -2166,6 +2173,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