Alternative iterator syntax

Jeff Petkau jpet at eskimo.com
Thu Feb 22 00:41:19 EST 2001


Huaiyu Zhu <hzhu at users.sourceforge.net> wrote in message
news:mailman.982769240.31345.python-list at python.org...
> Following suggestion by Jeff Petkau <jpet at eskimo.com>,
> (http://mail.python.org/pipermail/python-list/2001-February/029944.html),
> here is a different proposal for iterators.
...

As proposed, this would break existing classes that define
only spam.__getitem__() and expect 'for x in spam' to work.

It would be a much smaller change to leave 'for' alone,
using __getitem__(0,1,2...).  Or maybe adding the fallback
to __call__ if __getitem__ is not defined.

But I'm not sure this whole thing is a good idea.  How about
just some builtin functions for items(), keys(), values(),
and indexed() that return lazy iterators?

for k,v in items(mydict)
for k in keys(mydict)
for v in values(mydict)
for i,v in indexed(mysequence)

indexed() is easy:

    class indexed:
        def __init__(self,seq):
            self.seq = seq
        def __getitem__(self,i):
            return i,self.seq[i]

The others would require a special hook in dict. I'd prefer
an integer-indexed access function, but having it return an
iterator works too if you're into that sort of thing.

    class items:
        def __init__(self,d):
            self.dict = d
        def __getitem__(self,i):
            return i,self.dict.__getitem_n__(i)

--Jeff Petkau (jpet at eskimo.com)






More information about the Python-list mailing list