示例工程 04-containers-complexity

04-containers-complexity/03-hash-contract/hash_contract.py

python · 1.3 KB

"""演示 __eq__/__hash__ 契约:破坏后字典/集合会「找不到」。"""
 
from __future__ import annotations
 
 
class Point:
    """按值相等、按值哈希的可变对象。"""
 
    def __init__(self, x: int, y: int) -> None:
        self.x = x
        self.y = y
 
    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Point):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)
 
    def __hash__(self) -> int:
        return hash((self.x, self.y))
 
 
class EqOnly:
    """只实现 __eq__,因此不可哈希。"""
 
    def __eq__(self, other: object) -> bool:
        return isinstance(other, EqOnly)
 
 
def unhashable_error() -> str:
    try:
        _ = {[]: 1}
    except TypeError as exc:
        return str(exc)
    raise AssertionError("expected TypeError")
 
 
def eq_only_error() -> str:
    try:
        {EqOnly(): 1}
    except TypeError as exc:
        return str(exc)
    raise AssertionError("expected TypeError")
 
 
def mutated_key_is_lost() -> bool:
    point = Point(1, 2)
    table = {point: "value"}
    point.x = 9
    return point not in table
 
 
def main() -> None:
    print(f"list key: {unhashable_error()}")
    print(f"eq-only key: {eq_only_error()}")
    print(f"mutated key lost: {mutated_key_is_lost()}")
 
 
if __name__ == "__main__":
    main()