Lets say I have two functions:
def foo():
return 'foo'
def bar():
yield 'bar'
The first one is a normal function, and the second is a generator function. Now I want to write something like this:
def run(func):
if is_generator_function(func):
gen = func()
gen.next()
#... run the generator ...
else:
func()
What will a straightforward implementation of is_generator_function()
look like? Using the types
package I can test if gen
is a generator, but I wish to do so before invoking func()
.
Now consider the following case:
def goo():
if False:
yield
else:
return
An invocation of goo()
will return a generator. I presume that the python parser knows that the goo()
function has a yield statement, and I wonder if it possible to get that information easily.
Thanks!
yield
statement, then areturn
statement inside that function is not permitted to have an argument. It has to be justreturn
which terminates the generator. Good question!goo()
should not be valid, however it is, at least here (Python 2.6.2).