Message102918
The Python tutorial offers some dangerous advice about adding iterator behavior to a class:
http://docs.python.org/tutorial/classes.html#iterators
“By now you have probably noticed that most container objects can be looped over using a for statement:
…
Having seen the mechanics behind the iterator protocol, it is easy to add iterator behavior to your classes. Define a __iter__() method which returns an object with a next() method. If the class defines next(), then __iter__() can just return self:”
This is reasonable advice for writing an iterator class, but terrible advice for writing a container class, because it encourages you to associate a single iterator with the container, which breaks nested iteration and leads to hard-to-find bugs. (One of those bugs recently made its way into the code handout for a problem set in MIT’s introductory CS course, 6.00.)
A container class’s __iter__() should return a generator or an instance of a separate iterator class, not self. The tutorial should make this clearer. |
|
Date |
User |
Action |
Args |
2010-04-12 06:35:58 | andersk | set | recipients:
+ andersk, georg.brandl |
2010-04-12 06:35:58 | andersk | set | messageid: <1271054158.9.0.672918640444.issue8376@psf.upfronthosting.co.za> |
2010-04-12 06:35:57 | andersk | link | issue8376 messages |
2010-04-12 06:35:55 | andersk | create | |
|