Skip to content

Instantly share code, notes, and snippets.

@SakuraSa
Created May 30, 2015 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SakuraSa/e394df11c11629d14b9d to your computer and use it in GitHub Desktop.
Save SakuraSa/e394df11c11629d14b9d to your computer and use it in GitHub Desktop.
BetterGen with "has_next" property
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