Sub topic 13
Marking keys ReadOnly
This chapter assumes you can define a TypedDict with the class syntax, know that NotRequired marks an optional key, and run a static checker such as mypy or pyright. ReadOnly is available from typing in Python 3.13 and later. On older versions, import it from typing_extensions.
The problem
Some dictionary keys should be set once and never changed. An account id is a typical example. A plain TypedDict lets any code with a reference to the dictionary reassign every key, and the checker raises no complaint.
ReadOnly[...] wraps a key's type and tells the checker that code must not reassign that key.
Declaring a read-only key
from typing import ReadOnly, TypedDict
class Account(TypedDict):
id: ReadOnly[int]
balance: float
def deposit(account: Account, amount: float) -> None:
account["balance"] += amount # allowed
account["id"] = 0 # rejected by a type checker
acct: Account = {"id": 7, "balance": 10.0}
deposit(acct, 5.0)
print(acct)A checker reports an error on the account["id"] = 0 line. It reports no error for the balance line. The program above still runs and prints {'id': 0, 'balance': 15.0}, because the dictionary is a normal mutable dict at runtime.
What the checker blocks
A read-only key cannot be:
- Assigned to, as in
account["id"] = 0. - Deleted with
del. - Overwritten by
update()with a value that includes that key, when the checker can see the key in the argument's type.
Reading the key is always fine. Other keys in the same TypedDict keep their normal behavior.
Combining with optional keys
ReadOnly can sit inside or outside Required and NotRequired. Both spellings mean the same thing.
from typing import NotRequired, ReadOnly, TypedDict
class Profile(TypedDict):
id: ReadOnly[int]
nickname: NotRequired[ReadOnly[str]]
bio: str
p: Profile = {"id": 1, "bio": "Hello"}
if "nickname" in p:
print(p["nickname"])Here nickname may be absent, and if it is present, code must not reassign it.
Why read-only keys are more flexible in subtypes
Mutable keys are strict about types. If a function takes a TypedDict with balance: float, it might write a float into it, so a dictionary whose balance is narrower is not safe to pass in.
A read-only key is only ever read, so a narrower value type is safe. A TypedDict that declares id: ReadOnly[int] therefore accepts a dictionary type whose id is bool, since bool is a subtype of int. The same rule applies in inheritance: a child class may narrow the type of a read-only key from its parent.
Common mistakes
- Expecting a runtime error. The assignment succeeds at runtime, so tests alone will not catch it.
- Using
ReadOnlyon Python versions before 3.13 withouttyping_extensions. The import fails withImportError. - Treating
ReadOnlyas deep immutability. It protects the key's binding only. If the value is a list, code can still callappendon it. - Confusing it with
Final.Finalapplies to variables and class attributes, whileReadOnlyapplies only to keys inside aTypedDict.
Summary
Use ReadOnly[T] to document and enforce, in the type checker, that a key is set once. It combines freely with Required and NotRequired, and it relaxes subtype rules for that key. It does nothing at runtime, so use a dataclass with frozen=True or a validation library when you need real enforcement.
Exercise
A function receives an Account with id: ReadOnly[int] and runs account["id"] = 99. What do mypy or pyright report, and what happens when the program runs?
Show answer
The type checker reports an error on the assignment because the key is read-only. At runtime nothing is raised. The dictionary is an ordinary dict, so the value of id becomes 99.
Exercise
Write a TypedDict named Config with a required read-only key name of type str and an optional read-only key region of type str, using typing_extensions imports so it works before Python 3.13.
Show answer
from typing_extensions import NotRequired, ReadOnly, TypedDict class Config(TypedDict): name: ReadOnly[str] region: NotRequired[ReadOnly[str]]