How do you refer to an iterator in docs?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Apr 21 00:20:55 EDT 2012


On Fri, 20 Apr 2012 23:01:08 -0400, Roy Smith wrote:

> In article <4f921a2d$0$29965$c3e8da3$5496439d at news.astraweb.com>,
>  Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> 
>> On Fri, 20 Apr 2012 09:41:25 -0400, Roy Smith wrote:
>> 
>> > In article <4f910c3d$0$29965$c3e8da3$5496439d at news.astraweb.com>,
>> >  Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
>> > 
>> >> I refer you to your subject line:
>> >> 
>> >> "How do you refer to an iterator in docs?"
>> >> 
>> >> In documentation, I refer to an iterator as an iterator, just as I
>> >> would refer to a list as a list, a dict as a dict, or a string as a
>> >> string.
>> > 
>> > Except that "list of foos" and "sequence of foos" make sense from a
>> > grammar standpoint, but "iterator of foos" does not.  Or maybe it
>> > does?
>> 
>> Why wouldn't it make sense?
> 
> Because an iterator isn't a container.  I don't know, maybe it does make
> sense, but my first impression is that it sounds wrong.


Containers in Python are defined via the iteration protocol: an object is 
a container if you can say "item in container", and that works for 
iterators:

>>> it = iter("abcde")
>>> next(it)
'a'
>>> 'b' in it
True

Although it must be said that since membership testing consumes the item, 
perhaps it would have been better not to support it for iterators. But 
membership testing should work for anything that supports iteration, so 
either way you will surprise somebody.


> A basket of apples is a basket which contains apples, in the same way a
> list contains foos.  But an iterator doesn't contain anything.

That's arguable. You are assuming an implementation detail. An iterator 
may be a thin wrapper around some other sort of container, so in the 
sense it may contain objects. It may also support rewinding (although 
that is an extension to the normal iterator protocol, it is not 
*forbidden*). Not all iterators are lazy producers of data.

And even those that are, in some philosophical sense they do contain the 
value you care about. Some lazy iterator primes() which calculates the 
prime numbers lazily may not *actually* contain the infinite list of 
prime numbers, but in some sense every prime number is held by that 
iterator in potentia, just waiting to be retrieved.


> You
> wouldn't say, "a spigot of water", because the spigot isn't a container
> holding the water.  It is simply a mechanism for delivering the water in
> a controlled way.

Iterators are not simply the mechanism for delivering items. The iterator 
*protocol* is the mechanism, iterator *objects* are objects.



-- 
Steven



More information about the Python-list mailing list