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
>>>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With