Travis Griggs
Travis Griggs

Reputation: 22252

How does python know when to return a generator?

When I put a yield in function body, obviously. But that's not what I'm trying to ask. Given two simple functions in an interactive interpreter:

def myGenerator():
    yield 42

def myFunction():
    return 42

When I execute both I see:

>>> myGenerator()
<generator object myGenerator at 0xb7bf511c>
>>> myFunction()
42

But If inspect the myGenerator and myFunction objects, I don't see anything really different:

for attr in dir(myFunction):
    print(attr, getattr(myFunction, attr)

produces stuff that looks the same as myGenerator. Is there some magic bit hidden in the bowels of the function object, that the interpreter branches off of to discern whether to wrap the function invocation as a generator? Or is it done more decorator style, where the presence of the yield keyword caused the object bound as 'myGenerator' to be wrapped in some generator magic? Or something else...?

Upvotes: 4

Views: 235

Answers (1)

Steve Allison
Steve Allison

Reputation: 1111

"A generator function is an ordinary function object in all respects, but has the new CO_GENERATOR flag set in the code object's co_flags member."

From the PEP http://www.python.org/dev/peps/pep-0255/

 >>> generator_fn.__code__.co_flags
 >>> 99
 >>> normal_fn.__code__.co_flags
 >>> 67

Upvotes: 4

Related Questions