diff --git a/peps/pep-0728.rst b/peps/pep-0728.rst index 6785e937e62..b89f8b79824 100644 --- a/peps/pep-0728.rst +++ b/peps/pep-0728.rst @@ -123,6 +123,24 @@ Given the usage of pre-:pep:`692` type annotation for ``**kwargs`` in existing codebases, it will be valuable to accept and type extra items on TypedDict so that the old typing behavior can be supported in combination with ``Unpack``. +Previous Discussions +-------------------- + +The new features introduced in this PEP would address several long-standing feature +requests in the type system. Previous discussions include: + +- `Mypy issue `__ asking for a "final TypedDict" + (2019). While the discussion focuses on the ``@final`` decorator, the underlying feature request + would be addressed by this PEP. +- `Mailing list thread `__ + asking for a way to say that a ``TypedDict`` can contain arbitrary extra keys (2020). +- `Discussion `__ + about an extension of the ``Unpack`` mechanism introduced by :pep:`692` (2023). +- `PEP 705 `__ in an earlier + draft proposed a similar feature (2023); it was removed to keep that PEP simpler. +- `Discussion `__ + about an "exact" ``TypedDict`` (2024). + Rationale ========= @@ -747,12 +765,22 @@ valid definition that indicates all extra items must be ``None``.) How to Teach This ================= -The choice of the spelling ``"extra_items"`` is intended to make this -feature more understandable to new users compared to shorter alternatives like -``"extra"``. - -Details of this should be documented in both the typing spec and the -:mod:`typing` documentation. +The new features introduced in this PEP can be taught together with the concept +of inheritance as it applies to ``TypedDict``. A possible outline could be: + +- Basics of ``TypedDict``: a ``dict`` with a fixed set of keys and value types. +- ``NotRequired``, ``Required``, and ``total=False``: keys that may be missing. +- ``ReadOnly``: keys that cannot be modified. +- Inheritance: subclasses can add new keys. As a corollary, a value of a ``TypedDict`` + type may contain additional keys at runtime that are not specified in the type. +- ``closed=True``: disallowing additional keys and restricting inheritance. +- ``extra_items=VT``: allowing additional keys with a specified value type. + +The concept of a closed ``TypedDict`` should also be cross-referenced in documentation +for related concepts. For example, type narrowing with the ``in`` operator works +differently, perhaps more intuitively, with closed ``TypedDict`` types. In addition, when ``Unpack`` +is used for keyword arguments, a closed ``TypedDict`` can be useful to restrict the +allowed keyword arguments. Backwards Compatibility =======================