[Tutor] __iter__: one obvious way to do it

spir denis.spir at gmail.com
Sun Mar 7 16:07:41 CET 2010


[sorry, forgot the code]

Hello,

Below 6 working way to implement __iter__ for a container here simulated with a plain inner list.
Sure, the example is a bit artificial ;-)

1. __iter__ returns a generator _expression_
2. __iter__ *is* a generator
3. __iter__ returns a generator
   (this one is a bit weird, i guess)
4. __iter__ returns self, its own iterator via next()
5. __iter__ returns an external iterator object
6. __iter__ returns iter() of a collection built just on time
   (this one is really contrived)
Also, one can always traverse the collection (already existing or built then) itself if it not quasi-infinite (no __iter__ at all).

"There should be one-- and preferably only one --obvious way to do it"
http://www.python.org/dev/peps/pep-0020/ 

I understand some ways fit given use cases better -- or worse. But it's difficult to find the best one, or even a proper one in a given case. Also, generation and iteration are rather abstract notions. And it's too much variety for me. I am lost in this field.

I would enjoy a commented and examplified overview.

Denis

-----
class Seq(object):
    def __init__(self, *items):
        self.items = list(items)
    def next(self):
        if self.i < len(self.items):
            x = pair(self.items[self.i])
            self.i += 1
            return x
        raise StopIteration
    def pairs(l):
        for n in l.items:
            yield pair(n)
        raise StopIteration
    def __iter__(self):
        return (pair(n) for n in self.items)
    def __iter__(self):
        for n in self.items:
            yield pair(n)
        raise StopIteration
    def __iter__(self):
        return self.pairs()
    def __iter__(self):
        self.i=0
        return self
    def __iter__(self):
        return Iter(self)
    def __iter__(self):
        return iter(tuple([pair(n) for n in self.items]))
def pair(n): return "%s:%s" %(n,chr(n+96))
class Iter(object):
    def __init__(self, l):
        self.i=0
        self.items = l.items
    def __iter__(self):
        return self
    def next(self):
        if self.i < len(self.items):
            x = pair(self.items[self.i])
            self.i += 1
            return x
        raise StopIteration
    
l = Seq(1,2,3)
for x in l: print x,    # ==> 1:a 2:b 3:c

________________________________

la vita e estrany

spir.wikidot.com



More information about the Tutor mailing list