Skip to content

Commit 38526a2

Browse files
[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 f49958c) Co-authored-by: Jelle Zijlstra <[email protected]>
1 parent 448a707 commit 38526a2

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

Doc/library/typing.rst

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2131,6 +2131,13 @@ types.
21312131
>>> Point3D.__total__
21322132
True
21332133

2134+
This attribute reflects *only* the value of the ``total`` argument
2135+
to the current ``TypedDict`` class, not whether the class is semantically
2136+
total. For example, a ``TypedDict`` with ``__total__`` set to True may
2137+
have keys marked with :data:`NotRequired`, or it may inherit from another
2138+
``TypedDict`` with ``total=False``. Therefore, it is generally better to use
2139+
:attr:`__required_keys__` and :attr:`__optional_keys__` for introspection.
2140+
21342141
.. attribute:: __required_keys__
21352142

21362143
.. versionadded:: 3.9
@@ -2166,6 +2173,14 @@ types.
21662173

21672174
.. versionadded:: 3.9
21682175

2176+
.. note::
2177+
2178+
If ``from __future__ import annotations`` is used or if annotations
2179+
are given as strings, annotations are not evaluated when the
2180+
``TypedDict`` is defined. Therefore, the runtime introspection that
2181+
``__required_keys__`` and ``__optional_keys__`` rely on may not work
2182+
properly, and the values of the attributes may be incorrect.
2183+
21692184
See :pep:`589` for more examples and detailed rules of using ``TypedDict``.
21702185

21712186
.. versionadded:: 3.8

0 commit comments

Comments
 (0)