Iterator module (was: what *is* a class?)

Delaney, Timothy tdelaney at avaya.com
Tue Jun 18 20:10:08 EDT 2002


> From: holger krekel [mailto:pyth at devel.trillke.net]
> 
> Delaney, Timothy wrote:
> > > From: holger krekel [mailto:pyth at devel.trillke.net]
> >
> > iterable.sort(iterable [, func])
> > iterable.reverse(iterable)
> 
> that would be quite expensive for common cases (like lists).  
> reverse and 
> sort should also allow to operate on complete sequence types. 
> iterable.reverse could be cheap again then and iterable.sort would be
> as expensive as it is now (but not requiring any inplace-steps).

I disagree. The module I would propose is specifically for operating on
iterable objects (i.e. it is a general mechanism). Although there's nothing
stopping special-casing for common cases (such as tuples and lists) for
performance reasons if the semantics don't change.

It is also a *functional* module - nothing is modified in-place.

I'm also more inclined to call the module 'iterator' because ...

> > iterable.map(func, iterable, ...)
> > iterable.filter(func, iterable, ...)
> > iterable.reduce(func, iterable, ...)
> > iterable.zip(iterable, ...)
> > iterable.range([start,] stop[, step])
> 
> yes, indeed! i'd probably do 'from iterable import *' :-)

... these are *not* drop-in replacements for the similarly-named functions
in builtins. Specifically, every method returns an iterator (which excludes
reduce from the list).

    l = [ 3, 1, 2, ]
    s = iterator.sort(l)
    r = iterator.reverse(s)

    print l
    print s
    print r

What output do you expect?

> seriously, i'd include something like concat as an iterable, too: 
> 
>     for item in iterable.concat(iter1,iter2):
>         # items iterates with iter1, then iter2 
> 
> All the the iterable functions should accept sequence and 
> possibly mapping types (same semantics as for 'for'-loops now).

Nope - they would all accept iterable objects (where appropriate). Same
semantics as for 'for'-loops now (they call iter() on appropriate
parameters).

Things like extend() and concat() could be appropriate, but you could end up
calling:

    t = (1, 2, 3,)
    i = iterator.extend(t, 4)

which may or may not be considered a good thing.

> > There have been suggestions like this before, but I don't 
> recall one for
> > sort() and reverse(), and these two have fired me :)
> 
> I think an iterable module should be done. Although there would 
> inevitably be overlapping functionality with the current builtins.

Some overlapping, but the majority (all?) builtins return restartable
iterables (such as a list) rather than an iterator.

Tim Delaney





More information about the Python-list mailing list