Sub topic 13
Marking keys ReadOnly
This chapter assumes you can define a TypedDict, mark keys with NotRequired, and read the output of a type checker such as mypy or pyright. It covers ReadOnly, which lets a TypedDict declare that some keys must not be changed after the dictionary is created.
Why a dictionary needs read-only keys
A normal TypedDict key is mutable. Any function that receives the dictionary may assign to any key, and the checker allows it. That is a poor fit for fields that identify a record, such as an id, a creation timestamp, or a kind tag. Code that changes one of these fields usually has a bug.
ReadOnly marks such a key. A type checker then rejects assignments to it, deletions of it, and calls that could overwrite it. The dictionary stays mutable at runtime. ReadOnly is a promise that the checker enforces, not a lock.
ReadOnly was added by PEP 705. It is in typing from Python 3.13. On older versions, import it from typing_extensions:
try:
from typing import ReadOnly, TypedDict
except ImportError: # Python 3.12 and older
from typing_extensions import ReadOnly, TypedDictThe rest of this chapter imports from typing and assumes 3.13 or later.
Basic usage
Wrap the value type of a key in ReadOnly[...]:
from typing import ReadOnly, TypedDict
class Account(TypedDict):
id: ReadOnly[int]
balance: float
def deposit(account: Account, amount: float) -> None:
account["balance"] += amount # allowed: balance is mutable
account["id"] = 0 # rejected: id is read-only
acct: Account = {"id": 7, "balance": 10.0}
deposit(acct, 5.0)
print(acct)A checker reports the assignment to account["id"] as an error. Reading account["id"] is always fine. Creating the dictionary with an id value is also fine, because creation is not a change to an existing key.
The checker rejects these operations on a read-only key:
- Assignment:
account["id"] = 0. - Augmented assignment:
account["id"] += 1. - Deletion:
del account["id"]. pop,popitemandsetdefaultcalls that could remove or set the key.updatecalls whose argument type could carry a new value for that key.
Check the exact messages in your checker's output. Support for the update and setdefault cases has varied between tools and versions.
What the checker decides
Runtime behavior
Nothing changes when the program runs. The dictionary is a plain dict, so the assignment succeeds:
from typing import ReadOnly, TypedDict, get_type_hints
class Account(TypedDict):
id: ReadOnly[int]
balance: float
acct = Account(id=7, balance=10.0)
acct["id"] = 0 # a checker flags this line, but it runs without error
print(acct)
print(get_type_hints(Account))
print(sorted(Account.__readonly_keys__))
print(sorted(Account.__mutable_keys__))The class records which keys are which. On Python 3.13 and later, __readonly_keys__ and __mutable_keys__ are frozensets of key names. get_type_hints strips the ReadOnly wrapper by default and returns plain int and float. Pass include_extras=True to see ReadOnly[int].
This is the same split you saw with Literal and the other TypedDict features. The annotations are metadata for tools. If untrusted code can mutate your dictionary, ReadOnly does not protect you. For true immutability, use a frozen dataclass or types.MappingProxyType.
Combining ReadOnly with Required and NotRequired
ReadOnly can sit inside or outside Required and NotRequired. Both orders mean the same thing:
from typing import NotRequired, ReadOnly, TypedDict
class Document(TypedDict):
id: ReadOnly[int]
title: str
checksum: ReadOnly[NotRequired[str]]
note: NotRequired[ReadOnly[str]]
doc: Document = {"id": 1, "title": "Draft"}
if "checksum" in doc:
print(doc["checksum"])
print(sorted(Document.__readonly_keys__))With total=False, every key is optional, and you can still mark individual keys ReadOnly. Optional and read-only are separate properties of a key.
A key that is both optional and read-only can be present or absent, and neither the code that reads it nor the code that receives it may add or change it later.
Subtyping: read-only keys are covariant
The rules for passing one TypedDict where another is expected are where ReadOnly has the most effect. A mutable key is invariant: the value types must match exactly. A read-only key is covariant: a narrower value type is accepted.
from typing import ReadOnly, TypedDict
class Measurement(TypedDict):
value: ReadOnly[float]
class Count(TypedDict):
value: int
def show(m: Measurement) -> None:
print(f"value = {m['value']}")
show(Count(value=3)) # acceptedint is acceptable where float is expected, so the checker allows the call. If Measurement.value were a plain mutable float, the call would be an error. show could then store 2.5 in the key, and the original Count dictionary would hold a float where its type promises an int.
The reverse direction is stricter. A function that wants a mutable key will not accept a dictionary whose key is read-only:
from typing import ReadOnly, TypedDict
class Editable(TypedDict):
name: str
class Frozen(TypedDict):
name: ReadOnly[str]
def rename(item: Editable) -> None:
item["name"] = "changed"
frozen: Frozen = {"name": "fixed"}
rename(frozen) # rejected: Frozen.name is read-only but Editable.name is mutableIn the other direction, passing an Editable where a Frozen is expected is accepted. Handing a mutable key to code that promises not to write is safe.
| Parameter declares | Argument key is mutable | Argument key is read-only |
|---|---|---|
| Mutable key, type `T` | Accepted only if the value type is exactly `T` | Rejected |
| Read-only key, type `T` | Accepted if the value type is `T` or narrower | Accepted if the value type is `T` or narrower |
Narrowing keys in inheritance
Covariance also applies to subclasses. A child TypedDict may redeclare an inherited read-only key with a narrower type. A mutable key cannot be narrowed this way. This combines well with Literal:
from typing import Literal, ReadOnly, TypedDict
class Event(TypedDict):
kind: ReadOnly[str]
timestamp: float
class Click(Event):
kind: ReadOnly[Literal["click"]]
x: int
y: int
class KeyPress(Event):
kind: ReadOnly[Literal["key"]]
key: str
def log(event: Event) -> None:
print(event["kind"], event["timestamp"])
log(Click(kind="click", timestamp=1.5, x=10, y=20))Click and KeyPress share the base fields, and each fixes kind to its own constant. Because kind is read-only, the checker also stops code from changing an event's tag after creation. That keeps a tagged union consistent.
A read-only optional key can also be made required in a subclass. A mutable key cannot change between required and optional.
Choosing when to use ReadOnly
Use ReadOnly when:
- A field identifies a record, such as an
id, a tag, or a version, and should not change after creation. - A function takes a
TypedDictonly to read it, and you want callers to pass dictionaries whose value types are narrower than the declared ones. - A base
TypedDictfixes a set of fields that subclasses narrow withLiteral.
Skip it when:
- You need enforcement at runtime. Use a frozen dataclass,
NamedTuple, or a validation library. - Your type checker is older than the PEP 705 support and reports the annotation as unknown.
Common mistakes
- Expecting a
TypeErrorat runtime. The write succeeds, so tests that never run a checker will not notice a violation. - Using
ReadOnlyoutside aTypedDict. It is only valid for keys of aTypedDict, and checkers report it elsewhere, for example on a function parameter or a plain variable. - Passing a read-only-keyed dictionary to a function that mutates the key. The error appears at the call site, which can surprise people who only changed the callee's signature.
- Forgetting
typing_extensionson Python 3.12 and older.from typing import ReadOnlyraisesImportErrorthere.
Exercise
Given class Config(TypedDict): name: ReadOnly[str]; retries: int, a function def reset(cfg: Config) -> None: cfg["retries"] = 0; cfg["name"] = "x" is checked. Which line does the checker flag, and does the function raise an error when run on a plain dict?
Show answer
The checker flags cfg["name"] = "x" because name is read-only. Assigning cfg["retries"] = 0 is allowed. At runtime neither line raises an error, because the object is an ordinary dict and ReadOnly is not enforced.
Exercise
Why does a function with the parameter type class Wide(TypedDict): value: ReadOnly[float] accept a dictionary typed class Narrow(TypedDict): value: int, while the same function with value: float (mutable) does not?
Show answer
A read-only key is covariant, so int, which is acceptable where float is expected, is allowed. A mutable key is invariant. Code that receives a Wide with a mutable float key could write 2.5 into the key, which would break the Narrow dictionary's promise that value is an int.