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
>>>
yieldstatement differently. Once you put ayieldin there, it knows you'll be defining a generator, not a regular function. Try puttingyieldandreturn(with an argument) in the same function, Python won't let you compile that code, even if you never use that function.yieldstatement: "Using a yield statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function." How exactly the Python bytecode compilation process works is highly involved and shouldn't have to concern you.