diff options
author | Ivan Levkivskyi <levkivskyi@gmail.com> | 2019-05-26 08:39:24 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-05-26 08:39:24 (GMT) |
commit | 135c6a56e55d2f4f8718b3b9f03ce3c692b15f0f (patch) | |
tree | b585115cb0b9684430a7a3ffe02b2a0df584890a /Doc | |
parent | b891c465bb7d38a597c5c2ad547d7b19194f4dad (diff) | |
download | cpython-135c6a56e55d2f4f8718b3b9f03ce3c692b15f0f.zip cpython-135c6a56e55d2f4f8718b3b9f03ce3c692b15f0f.tar.gz cpython-135c6a56e55d2f4f8718b3b9f03ce3c692b15f0f.tar.bz2 |
bpo-37049: PEP 589: Add TypedDict to typing module (GH-13573)
The implementation is straightforward and essentially is just copied from `typing_extensions`.
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/library/typing.rst | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index e64fecb..27787fc 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -878,6 +878,39 @@ The module defines the following classes, functions and decorators: The ``_field_types`` and ``__annotations__`` attributes are now regular dictionaries instead of instances of ``OrderedDict``. +.. class:: TypedDict(dict) + + A simple typed namespace. At runtime it is equivalent to + a plain :class:`dict`. + + ``TypedDict`` creates a dictionary type that expects all of its + instances to have a certain set of keys, where each key is + associated with a value of a consistent type. This expectation + is not checked at runtime but is only enforced by type checkers. + Usage:: + + class Point2D(TypedDict): + x: int + y: int + label: str + + a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK + b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check + + assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') + + The type info for introspection can be accessed via ``Point2D.__annotations__`` + and ``Point2D.__total__``. To allow using this feature with older versions + of Python that do not support :pep:`526`, ``TypedDict`` supports two additional + equivalent syntactic forms:: + + Point2D = TypedDict('Point2D', x=int, y=int, label=str) + Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) + + See :pep:`589` for more examples and detailed rules of using ``TypedDict`` + with type checkers. + + .. versionadded:: 3.8 .. function:: NewType(typ) |