Skip to content

Instantly share code, notes, and snippets.

@LilyFoote
Last active March 8, 2021 22:30
Show Gist options
  • Save LilyFoote/e381d88fbbd4f6d3b90c to your computer and use it in GitHub Desktop.
Save LilyFoote/e381d88fbbd4f6d3b90c to your computer and use it in GitHub Desktop.
A reusable generator
def reusable(generator):
"""Convert a generator into a ReusableIterator."""
class ReusableIterator:
"""Create an wrapper for a generator to allow repeated iteration."""
def __init__(self, *args, **kwargs):
"""Store the arguments to pass to the wrapped generator."""
self.args = args
self.kwargs = kwargs
def __iter__(self):
"""Return an iterator that yields values from the generator."""
yield from generator(*self.args, **self.kwargs)
return ReusableIterator
@valorien
Copy link

valorien commented May 2, 2015

Nice solution :-)
There's a typo in the return statement BTW. Should be return ReusableIterator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment