Frozen Dataclasses As Hashable Keys
Make dataclasses safe dictionary keys and set members with frozen=True and eq, so value semantics replace tuples of fields.
Code
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
def main() -> None:
# frozen + eq:值相等、可哈希,直接当键与集合成员
cache: dict[Point, str] = {}
cache[Point(1, 2)] = 'origin-ish'
cache[Point(3, 4)] = 'far'
print(cache[Point(1, 2)]) # 值相等即命中,无需同一个实例
visited = {Point(0, 0), Point(1, 2), Point(0, 0)}
print('unique visited:', len(visited))
# 冻结也意味着不可变:赋值会抛 FrozenInstanceError
p = Point(5, 6)
try:
p.x = 9 # type: ignore[misc]
except Exception as exc:
print('immutable:', type(exc).__name__)
# 需要变更时用 replace 生成新实例
from dataclasses import replace
moved = replace(p, x=9)
print('moved:', moved, 'original:', p)
if __name__ == '__main__':
main()Output
Captured from a sandboxed run of this snippet in the build pipeline.
origin-ish
unique visited: 2
immutable: FrozenInstanceError
moved: Point(x=9, y=6) original: Point(x=5, y=6)How it works
Count the class Point and the function main as the entire surface area of Frozen Dataclasses As Hashable Keys.
Applying it
The primary signature is def main() -> None
The demo output is labeled (unique visited:, immutable:, moved:), so every printed line maps back to its originating operation.
Statements that matter
except Exception as exc:
print('immutable:', type(exc).__name__)
@dataclass(frozen=True)
class Point:
x: int
y: int
def main() -> None:
# frozen + eq:值相等、可哈希,直接当键与集合成员
cache: dict[Point, str] = {}
Interactive Tools for This Topic
FAQ
- What does Frozen Dataclasses As Hashable Keys print when run?
- Run it as a complete program — the output lines carry labels such as `unique visited:`, `immutable:`, `moved:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.