Created
May 30, 2015 07:29
-
-
Save SakuraSa/e394df11c11629d14b9d to your computer and use it in GitHub Desktop.
BetterGen with "has_next" property
This file contains 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
class BetterGen(object): | |
""" | |
BetterGen | |
""" | |
def __init__(self, gen): | |
self.gen = gen | |
self._next = None | |
self._stoped = False | |
self.try_next() | |
def try_next(self): | |
try: | |
self._next = next(self.gen) | |
except StopIteration: | |
self._stoped = True | |
def next(self): | |
if self._stoped: | |
raise StopIteration() | |
else: | |
value = self._next | |
self.try_next() | |
return value | |
def __iter__(self): | |
def iter_func(): | |
while self.has_next: | |
yield self.next() | |
return iter_func() | |
@property | |
def has_next(self): | |
return not self._stoped | |
if __name__ == '__main__': | |
g1 = BetterGen(iter("Hello world!")) | |
print g1.has_next | |
print ''.join(c for c in g1) | |
g2 = BetterGen(iter("")) | |
print g2.has_next | |
# output: | |
# >> True | |
# >> Hello world! | |
# >> False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment