示例工程 17-generators-coroutines

17-generators-coroutines/01-generator-state-machine/generator_state_machine.py

python · 0.7 KB

"""演示 send 驱动的累加器状态机。"""
 
from __future__ import annotations
 
from collections.abc import Generator
 
 
def accumulator() -> Generator[int, int | None, None]:
    total = 0
    while True:
        value = yield total
        if value is None:
            return
        total += value
 
 
def main() -> None:
    gen = accumulator()
    print(f"start: {next(gen)}")
    print(f"after 5: {gen.send(5)}")
    print(f"after 7: {gen.send(7)}")
    try:
        gen.send(None)
    except StopIteration:
        print("finished: True")
 
    fresh = accumulator()
    try:
        fresh.send(1)
    except TypeError as exc:
        print(f"first send error: {exc}")
 
 
if __name__ == "__main__":
    main()