[Python-ideas] Generators are iterators
Steven D'Aprano
steve at pearwood.info
Thu Dec 11 01:30:32 CET 2014
On Wed, Dec 10, 2014 at 05:11:43PM -0500, Alexander Belopolsky wrote:
> I think the problem is with the term "generator function" because what we
> call "generator function" is neither a generator nor a function.
I'm afraid that is just wrong. "Generator functions" are functions.
py> def gen():
... yield 1
...
py> type(gen)
<class 'function'>
They are distinguishable from other functions by the presence of a flag
on the __code__ object. The ``isgeneratorfunction`` function in the
inspect module is short enough to reproduce here:
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.__code__.co_flags & CO_GENERATOR)
Generator functions are essentially syntactic sugar for building
iterators from coroutines. The specific type of iterator they return is
a generator, which is a built-in type (but not a built-in name).
--
Steven
More information about the Python-ideas
mailing list