Odd closure issue for generators

Terry Reedy tjreedy at udel.edu
Sat Jun 6 17:25:05 EDT 2009

Michele Simionato wrote:

> Yes, most functional languages have the concept of streams.
> You can even define a stream-comprehension that looks like
> Python generator comprehension but it is an essentially different
> thing. See for instance
> http://www.artima.com/weblogs/viewpost.jsp?thread=251159

I read that.  It seems that streams are virtual or lazy linked-lists(1). 
  I think, though, that comparing them to iterators is misleading.  They 
are iterables, but with a different iteration protocol.  Python 
iterables are generally reiterable just like streams.

chars = 'abc'
for c in chars: print(c,end=' ')
for c in chars: print(c,end=' ')

produces repeatable output just like your stream example.  Python 
*could* have given iterables .first and .rest methods instead of 
.__iter__, but that works best for linked lists and awfully for arrays.

Anyway, I realize now that having generator comprehensions produce an 
*iterator* rathar than an *iterable* or *generator function* is 
something of an anomaly  Set, dict, and list comprehensions in Python 
produce iterables, of course, as does a stream comprehension in Scheme 
and, I presume, comprehensions in other languages.

A generator expression could have been defined in Python to just produce 
a generator function, without calling it, but the intent of the 
abbreviation was for one-use situations.  Multi-use gfs should be 
defined with a def statement.

Terry Jan Reedy

(1) Calling the first and rest methods 'car' and 'cdr' convinces me that 
schemers really do not want scheme to be popular, but prefer it to 
remain a small cult language.

More information about the Python-list mailing list