CKTIS / Python
dataclasses.dataclass
Generates methods such as an initializer and value-based equality from the annotated fields of a class.
Version: Python 3.14; repository image, production runtime not attested
Syntax
@dataclasses.dataclass(frozen=True)Generates methods such as an initializer and value-based equality from the annotated fields of a class.
A frozen data class rejects field assignment after initialization. Comparisons use fields and the exact class.
Annotate fields in declaration order to generate an initializer, representation and value comparison by default. Generated equality uses comparison fields of instances of the same exact class. With frozen=True rebinding a field raises FrozenInstanceError, though a list stored in that field can still change. The sample's two Point(4) instances compare equal. With no explicit __hash__, eq=True plus frozen=True generates a hash; eq=True without frozen disables hashing, and eq=False retains the inherited rule. unsafe_hash=True forces generation. slots=True returns a new class. Fields from bases are collected in reverse MRO, with overrides retaining their positions. A generated hash method still hashes the participating fields. hash(Item([])) raises TypeError because the stored list is unhashable.
from dataclasses import dataclass, FrozenInstanceError
@dataclass(frozen=True)
class Item:
tags: list
x = Item([])
x.tags.append("ok")
assert x == Item(["ok"])
try:
x.tags = []
except FrozenInstanceError:
pass
else:
raise AssertionError
class C: pass
assert dataclass(slots=True)(C) is not C
assert dataclass()(type("A", (), {})).__hash__ is None
assert callable(dataclass(frozen=True)(type("B", (), {})).__hash__)
try:
hash(Item([]))
except TypeError:
pass
else:
raise AssertionError
Examples
import dataclasses
@dataclasses.dataclass(frozen=True)
class Point:
x: int
p = Point(4)
print(p == Point(4))
try:
p.x = 9
except dataclasses.FrozenInstanceError as error:
print(type(error).__name__)
Result
True FrozenInstanceError
Annotate fields in declaration order to generate an initializer, representation and value comparison by default. Generated equality uses comparison fields of instances of the same exact class. With frozen=True rebinding a field raises FrozenInstanceError, though a list stored in that field can still change. The sample's two Point(4) instances compare equal. With no explicit `__hash__`, eq=True plus frozen=True generates a hash; eq=True without frozen disables hashing, and eq=False retains the inherited rule. unsafe_hash=True forces generation. slots=True returns a new class. Fields from bases are collected in reverse MRO, with overrides retaining their positions. A generated hash method still hashes the participating fields. hash(Item([])) raises TypeError because the stored list is unhashable.