Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 263
Niccolò Avatar asked Jul 05 '26 08:07

Niccolò


2 Answers

One does not invoke generator functions the same way one invokes normal functions. A generator function, when invoked, does not run but instead returns an iterator. This iterator, when passed to next() or used in other iteration contexts, invokes the original function:

>>> def f1(s):
...   print(s)
...   yield
... 
>>> it = f1("hello")
>>> next(it)
hello
>>> 

To follow up on the discussion in another answer, here is a way to invoke either a regular function or a generator function:

>>> def f0(s):
...   print s
... 
>>> def f1(s):
...   print s
...   yield
... 
>>> try: next(f0("hello"))
... except TypeError: pass
... 
hello
>>> try: next(f1("hello"))
... except TypeError: pass
... 
hello
>>> 
like image 165
Robᵩ Avatar answered Jul 08 '26 03:07

Robᵩ


You need to call next or the code in the generator won't run at all.

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').next()

bar = foo()
bar.run()

That prints "good" then "not good".

like image 23
Shashank Avatar answered Jul 08 '26 04:07

Shashank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!