"""复现默认对象共享与闭包延迟绑定。"""
def bad_add(value, bucket=[]):
    bucket.append(value)
    return bucket


def good_add(value, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(value)
    return bucket


def make_counter():
    count = 0

    def increment():
        nonlocal count
        count += 1
        return count

    return increment


def main():
    first = bad_add("a")
    second = bad_add("b")
    assert first is second and first == ["a", "b"]
    assert bad_add.__defaults__[0] is first
    assert good_add("a") == ["a"] and good_add("b") == ["b"]
    bad = [lambda: index for index in range(3)]
    good = [lambda index=index: index for index in range(3)]
    assert [fn() for fn in bad] == [2, 2, 2]
    assert [fn() for fn in good] == [0, 1, 2]
    counter = make_counter()
    assert (counter(), counter()) == (1, 2)
    assert counter.__closure__[0].cell_contents == 2
    # 在任务创建后改变配置，区分标量快照与可变引用。
    config = {"timeout": 10}
    late = lambda: config["timeout"]
    snapshot = lambda timeout=config["timeout"]: timeout
    shared = lambda config=config: config["timeout"]
    config["timeout"] = 20
    assert (late(), snapshot(), shared()) == (20, 10, 20)
    def broken():
        count += 1  # 赋值让 count 成为局部名称，读取时尚未绑定。
    try:
        broken()
    except UnboundLocalError:
        print("unbound local reproduced")
    else:
        raise AssertionError("expected UnboundLocalError")
    print("task late/scalar/shared:", late(), snapshot(), shared())
    print("default:", first)
    print("closures:", [fn() for fn in bad], [fn() for fn in good])


if __name__ == "__main__":
    main()
