How to make an empty generator?

Terry Reedy tjreedy at udel.edu
Fri Feb 19 14:25:21 EST 2010


On 2/19/2010 12:44 PM, Stephen Hansen wrote:

> Much to my embarrassment, sometime last night I realized I was being a
> complete idiot, and the 'correct' way to handle this in my scenario is
> really just:
>
> def initialize():
>      # do one time processing here
>
>      return []
>
> A generator is just a callable that returns an iterator, after all.

Confusing generators and generator functions is, well, confusing.
For future reference, and clarity of communication in Pythonland,

generator function: function that produces a generator when called; if 
python coded, its body contains 'yield'.

generator: iterator produced by a generator function; has .__next__ and 
self-returning .__init__, like all other iterators.

generator expression: an expression that evaluates to a generator; the 
expression is used to create a temporary anonymous generator function 
that is called to produce the generator and is then discarded.

 >>> def gf(): yield 1

 >>> gf
<function gf at 0x00F5F4B0>
 >>> g=gf()
 >>> g
<generator object gf at 0x00F5BE40>
 >>> ge = (1 for i in [1])
 >>> ge
<generator object <genexpr> at 0x00F5BFD0>
 >>> dir(ge)
[..., '__iter__', ..., '__next__', ...]

So, when you said that you send 'generators' to your core system, when 
you meant 'generator functions', we were understanably confused. (Your 
core system should accept iterator classes also, unless it specifically 
checks to avoid duck typing.)

Terry Jan Reedy




More information about the Python-list mailing list