def reuse(func=None, *, cache=lru_cache()):
"""Cache and reuse a generator function across multiple calls."""
# Allow this decorator to work with or without being called
if func is None:
return partial(reuse, cache=cache)
# Either initialize an empty history and start a new generator, or
# retrieve an existing history and the already-started generator
# that produced it
@cache
def resume(*args, **kwargs):
return [], func(*args, **kwargs)
@wraps(func)
def reuser(*args, **kwargs):
history, gen = resume(*args, **kwargs)
yield from history
record = history.append # Avoid inner-loop name lookup
for x in gen:
record(x)
yield x
return reuser
评论列表
文章目录