Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How python interpret a function as a generator

I know that if a "yield" statement is present in a function it will be treated as a generator. But how does python interpreter works in that case when the function(generator) called for the first time.I mean when the code is interpreted i think first "gen" will get bind to a function object. Why it doesn't execute the statements before yield unlike normal functions or classes when called for first time. How does it put a hold on the execution of the print function before yield

>>> def gen():
...    print("In gen")
...    yield 1
...    yield 2
... 
>>> type(gen)
<type 'function'>
>>> a = gen
>>> type(a)
<type 'function'>
>>> 
>>> b = a()
>>> type(b)
<type 'generator'>
>>> b.next()
In gen
1
>>> b.next()
2
>>> 
like image 509
bluefoggy Avatar asked Sep 14 '14 16:09

bluefoggy


1 Answers

When Python parses the def statement, it decides if the code is defining a generator or a function. If the code contains a yield expression, then it is a generator. So when the generator function a is called, it returns a generator object, b.

The code inside the def statement is not executed until b.next() is called.


Consider these two functions:

def gen():
     print('In gen')
     yield 1
     yield 2


def func():
     print('In gen')    

Although gen and func are both functions, Python knows that gen is a generator:

In [96]: import inspect

In [101]: inspect.isgeneratorfunction(gen)
Out[101]: True

In [102]: inspect.isgeneratorfunction(func)
Out[102]: False

If you look inside the inspect module you see

def isgeneratorfunction(object):
    """Return true if the object is a user-defined generator function.

    Generator function objects provides same attributes as functions.

    See help(isfunction) for attributes listing."""
    return bool((isfunction(object) or ismethod(object)) and
                object.func_code.co_flags & CO_GENERATOR)

So apparently Python checks this first before executing the code inside the function.

like image 98
unutbu Avatar answered Oct 13 '22 02:10

unutbu