Python Glossary Русский

Python 3.7+dataclassesfunction

@dataclass(frozen=True)

basics

frozen=True makes the instances immutable (like a namedtuple) and hashable.

Syntax

@dataclass(frozen=True)
class Pt:
    x: int; y: int

The freeze is shallow: you cannot rebind an attribute (FrozenInstanceError), but a list stored inside can still be appended to — and the object's hash breaks with it. Hashability comes specifically from frozen=True together with eq=True (the default); with plain eq=True and no freeze, dataclass sets __hash__ = None and the object stops working as a dict key. To change a value, use dataclasses.replace(), which returns a fresh instance, rather than assignment.

Examples

from dataclasses import dataclass
@dataclass(frozen=True)
class Pt:
    x: int
    y: int
p = Pt(1, 2)
print(p.x)  # → 1
print(hash(p) == hash(Pt(1, 2)))  # → True — замороженный объект хэшируем
d = {p: 'origin'}
print(d[Pt(1, 2)])  # → origin — равные по полям объекты дают один ключ
p.x = 5  # → FrozenInstanceError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy