How to make an empty generator?

John Posner jjposner at optimum.net
Fri Feb 19 21:16:05 CET 2010


On 2/19/2010 2:25 PM, Terry Reedy wrote:
> 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;

I suggest:

  iterator produced by a generator function or a generator expression;

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.

Note that the Py2.6.4 documentation is inconsistent. AFAICT, it conforms 
to Terry's definitions above in most places. But the Glossary says:

  generator
     A function which returns an iterator. <... more ...>

  generator expression
     An expression that returns a generator.  <... more ...>

The additional verbiage in these definitions mitigates the damage, but I 
think the first entry should be headlined *generator function* instead 
of *generator*. And the Glossary should include Terry's additional entry 
[ as amended by me :-) ]:

  generator
     An iterator produced by a generator function or a generator
     expression.

-John




More information about the Python-list mailing list