[Tutor] __iter__: one obvious way to do it

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


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"

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.


la vita e estrany


More information about the Tutor mailing list