Skip to content

Commit c5d3673

Browse files
JukkaLsobolevn
andcommitted
Document ReadOnly (PEP 705) (#17905)
Add basic documentation for mypy 1.12 release. --------- Co-authored-by: sobolevn <[email protected]>
1 parent 964a7a5 commit c5d3673

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

docs/source/typed_dict.rst

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,46 @@ another ``TypedDict`` if all required keys in the other ``TypedDict`` are requir
236236
first ``TypedDict``, and all non-required keys of the other ``TypedDict`` are also non-required keys
237237
in the first ``TypedDict``.
238238

239+
Read-only items
240+
---------------
241+
242+
You can use ``typing.ReadOnly``, introduced in Python 3.13, or
243+
``typing_extensions.ReadOnly`` to mark TypedDict items as read-only (:pep:`705`):
244+
245+
.. code-block:: python
246+
247+
from typing import TypedDict
248+
249+
# Or "from typing ..." on Python 3.13+
250+
from typing_extensions import ReadOnly
251+
252+
class Movie(TypedDict):
253+
name: ReadOnly[str]
254+
num_watched: int
255+
256+
m: Movie = {"name": "Jaws", "num_watched": 1}
257+
m["name"] = "The Godfather" # Error: "name" is read-only
258+
m["num_watched"] += 1 # OK
259+
260+
A TypedDict with a mutable item can be assigned to a TypedDict
261+
with a corresponding read-only item, and the type of the item can
262+
vary :ref:`covariantly <variance-of-generics>`:
263+
264+
.. code-block:: python
265+
266+
class Entry(TypedDict):
267+
name: ReadOnly[str | None]
268+
year: ReadOnly[int]
269+
270+
class Movie(TypedDict):
271+
name: str
272+
year: int
273+
274+
def process_entry(i: Entry) -> None: ...
275+
276+
m: Movie = {"name": "Jaws", "year": 1975}
277+
process_entry(m) # OK
278+
239279
Unions of TypedDicts
240280
--------------------
241281

0 commit comments

Comments
 (0)