"""演示 frozen 的可哈希性与「浅冻结」陷阱。""" from __future__ import annotations from dataclasses import FrozenInstanceError, dataclass @dataclass(frozen=True) class Point: x: int y: int @dataclass class MutablePoint: x: int @dataclass(frozen=True) class Box: items: list[int] def main() -> None: point = Point(1, 2) table = {point: "here"} print(f"hash_equal: {hash(point) == hash(Point(1, 2))}") print(f"lookup: {table[Point(1, 2)]}") try: point.x = 3 # type: ignore[misc] # 演示 frozen 运行时拦截 except FrozenInstanceError as exc: print(f"frozen: {exc}") print(f"mutable hash is None: {MutablePoint.__hash__ is None}") try: hash(MutablePoint(1)) except TypeError as exc: print(f"unhashable: {exc}") box = Box([1]) box.items.append(2) print(f"inner mutated: {box.items}") if __name__ == "__main__": main()