How does python know when to return a generator?

When I put the yield body in the function body, obviously. But this is not what I am trying to ask. Given two simple functions in an interactive interpreter:

 def myGenerator(): yield 42 def myFunction(): return 42 

When I do both, I see:

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

But if I check the objects myGenerator and myFunction , I see nothing else:

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

creates material that looks just like myGenerator . Is there some kind of magic bit hidden in the bowels of a functional object that the interpreter separates to determine whether to end the function call as a generator? Or is it done more in the style of a decorator, where the presence of the yield keyword caused the object to be bound as 'myGenerator' to some kind of generator magic? Or something else...?

+4
source share
1 answer

"The generator function is a normal function object in every way, but it has a new flag CO_GENERATOR set in the co_flags element of the code object."

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

  >>> generator_fn.__code__.co_flags >>> 99 >>> normal_fn.__code__.co_flags >>> 67 
+4
source

Source: https://habr.com/ru/post/1492182/


All Articles