Thursday, 12 September 2013

dynamic call of functions and generator function (python)

dynamic call of functions and generator function (python)

The following code only prints "good". Why the generator function is not
executed? I noticed with pdb that after executing 'handlers1' the script
reaches the line with f1's definition but then does not get inside the
function. Conversely, it's returned 'GeneratorExit: None'.
class foo:
def f0(self, s):
print s
def f1(self, s):
print "not " + s
yield 1
def run(self):
handlers={0 : self.f0, 1 : self.f1}
handlers[0]('good')
handlers[1]('good')
bar = foo()
bar.run()
Why this happens? Is it possible to call generator functions in a similar
dynamic way?

No comments:

Post a Comment