Skip to content

Instantly share code, notes, and snippets.

@LilyFoote
Last active March 8, 2021 22:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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
@LilyFoote
Copy link
Author

Inspired by the example LoadCities class given in Brett Slatkin - How to Be More Effective with Functions - PyCon 2015.

@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