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...?