Last active
March 8, 2021 22:30
-
-
Save LilyFoote/e381d88fbbd4f6d3b90c to your computer and use it in GitHub Desktop.
A reusable generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice solution :-)
There's a typo in the return statement BTW. Should be return ReusableIterator