Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document ReadOnly (PEP 705) #17905

Merged
merged 2 commits into from
Oct 9, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions docs/source/typed_dict.rst
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,46 @@ another ``TypedDict`` if all required keys in the other ``TypedDict`` are requir
first ``TypedDict``, and all non-required keys of the other ``TypedDict`` are also non-required keys
in the first ``TypedDict``.

Read-only items
---------------

You can use ``typing.ReadOnly``, introduced in Python 3.13, or
``typing_extensions.ReadOnly`` to mark TypedDict items as read-only (:pep:`705`):

.. code-block:: python

from typing import TypedDict

# Or "from typing ..." on Python 3.13
JukkaL marked this conversation as resolved.
Show resolved Hide resolved
from typing_extensions import ReadOnly

class Movie(TypedDict):
name: ReadOnly[str]
num_watched: int

m: Movie = {"name": "Jaws", "num_watched": 1}
m["name"] = "The Godfather" # Error: "name" is read-only
m["num_watched"] += 1 # OK

A TypedDict with a mutable item can be assigned to a TypedDict
with a corresponding read-only item, and the type of the item can
vary :ref:`covariantly <variance-of-generics>`:

.. code-block:: python

class Entry(TypedDict):
name: ReadOnly[str | None]
year: ReadOnly[int]

class Movie(TypedDict):
name: str
year: int

def process_entry(i: Entry) -> None: ...

m: Movie = {"name": "Jaws", "year": 1975}
process_entry(m) # OK

Unions of TypedDicts
--------------------

Expand Down