[Python-iterators] While we're at it...

Tim Peters tim.one at home.com
Fri Jun 29 16:32:56 EDT 2001


[Michael Chermside]
> ..,
> I agree we should modify a number of std library functions
> to use iterators, but random.choice seems to me to be a
> very poor (excuse the pun!) choice.

Do you have specific ones in mind?  Of course *anything* using

    for ... in x:

will automatically accept any x implementing the iterator interface,
including all 2.1 sequence types (even those supplied by pre-2.2 extension
modules that never heard of the iterator interface), and generators.  I
tried to cover other reasonable cases (no, not random.choice()) too, but
have certainly missed some.  Here's from (what will become) the 2.2 NEWS
file:

- Iterators were added; this is a generalized way of providing values
  to a for loop.  See PEP 234.  There's a new built-in function iter()
  to return an iterator.  There's a new protocol to get the next value
  from an iterator using the next() method (in Python) or the
  tp_iternext slot (in C).  There's a new protocol to get iterators
  using the __iter__() method (in Python) or the tp_iter slot (in C).
  Iterating (i.e. a for loop) over a dictionary generates its keys.
  Iterating over a file generates its lines.

- The following functions were generalized to work nicely with iterator
  arguments:
    map(), filter(), reduce(), zip()
    list(), tuple() (PySequence_Tuple() and PySequence_Fast() in C API)
    max(), min()
    join() method of strings
    extend() method of lists
    'x in y' and 'x not in y' (PySequence_Contains() in C API)
    operator.countOf() (PySequence_Count() in C API)
    right-hand side of assignment statements with multiple targets, such
    as
        x, y, z = some_iterable_object_returning_exactly_3_values

Anything else come to mind?  The core language coverage is pretty broad
already, so lots of stuff in the .py libraries should "just work by magic"
with any iterable argument.  OTOH, we all have blind spots, and, e.g., I
never would have thought of the "right-hand side of a multiple-target
assignment stmt" context on my own.





More information about the Python-list mailing list