"""演示可变默认参数只求值一次导致的累积污染。""" from __future__ import annotations # verify: allow-mutable-default # 本章主题 def append_bad(value: int, bucket: list[int] = []) -> list[int]: """错误写法:默认列表在定义时创建一次,被所有调用共享。""" bucket.append(value) return bucket def append_good(value: int, bucket: list[int] | None = None) -> list[int]: """正确写法:默认 None,调用时创建新列表。""" if bucket is None: bucket = [] bucket.append(value) return bucket def compare() -> dict[str, object]: first = append_bad(1) second = append_bad(2) return { "same_object": first is second, "bad_values": second, "good_first": append_good(1), "good_second": append_good(2), } def main() -> None: facts = compare() print(f"same_object: {facts['same_object']}") print(f"bad_values: {facts['bad_values']}") print(f"good_first: {facts['good_first']}") print(f"good_second: {facts['good_second']}") if __name__ == "__main__": main()