From e055b3ad12f6b90237b22d797a4c9d45284459b8 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Wed, 9 Oct 2024 11:24:22 +0100 Subject: [PATCH 1/2] Document ReadOnly (PEP 705) Add basic documentation for mypy 1.12 release. --- docs/source/typed_dict.rst | 40 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/docs/source/typed_dict.rst b/docs/source/typed_dict.rst index e69b3895c668..594fe0888ae3 100644 --- a/docs/source/typed_dict.rst +++ b/docs/source/typed_dict.rst @@ -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 + 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 `: + +.. 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 -------------------- From 9c3959634129d5ece9aaa24cb83c10147b89c5ac Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Wed, 9 Oct 2024 14:57:00 +0100 Subject: [PATCH 2/2] Update docs/source/typed_dict.rst Co-authored-by: sobolevn --- docs/source/typed_dict.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/typed_dict.rst b/docs/source/typed_dict.rst index 594fe0888ae3..bbb10a12abe8 100644 --- a/docs/source/typed_dict.rst +++ b/docs/source/typed_dict.rst @@ -246,7 +246,7 @@ You can use ``typing.ReadOnly``, introduced in Python 3.13, or from typing import TypedDict - # Or "from typing ..." on Python 3.13 + # Or "from typing ..." on Python 3.13+ from typing_extensions import ReadOnly class Movie(TypedDict):