Skip to content

Instantly share code, notes, and snippets.

@durden
Created January 7, 2013 20:31
Show Gist options
  • Save durden/4478134 to your computer and use it in GitHub Desktop.
Save durden/4478134 to your computer and use it in GitHub Desktop.
Little experiment with ways to override generator method and the caveats associated with it in Python.
class base(object):
def gen(self):
for ii in [1,2,3]:
yield ii
class child(base):
def gen(self):
for ii in [4,5,6]:
yield ii
super(child, self).gen()
b = base()
for x in b.gen(): print x
c = child()
for x in c.gen(): print x
# This does what you expect; yielding a generator object
# But then we would need multiple levels of looping and would be ugly to
# determine if the object that was returned (yielded) and then loop again;
# sounds like a weird recursion and infinite rabbit hole to achieve a correct
# and complete solution.
class child(base):
def gen(self):
for ii in [4,5,6]:
yield ii
yield super(child, self).gen()
# The 'correct' way to override generator method
class child(base):
def gen(self):
for ii in [4,5,6]:
yield ii
for ii in super(child, self).gen():
yield ii
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment