docs on for-loop with no __iter__?

Steven Bethard steven.bethard at gmail.com
Tue Sep 7 03:44:37 EDT 2004


Alex Martelli <aleaxit <at> yahoo.com> writes:
> > If no code would have been broken, I don't see why it would be 
> > unreasonable to use a more intuitive protocol.  
> 
> It may seem more intuitive to programmers trained in languages where
> exceptions are to be used as little as feasible, but to a
> dyed-in-the-wool Pythonista it doesn't.  Your proposed protocol would be
> more complicated than the historical one, since it would have to cover
> both classes that expose __len__ and ones that don't, in different ways,
> while the historical one is simpler because it does not need to draw
> that distinction, and "simpler is better than complicated" is a very
> important design principle in Python.

Well, my logic here was something along the lines of:

If you've provided a __len__ method and a __getitem__ that returns items for 
each index, then you've already provided all the necessary information for 
iteration.  If the __getitem__ also has to raise an IndexError when the index 
exceeds the length, in some sense, you're duplicating information -- both 
__len__ and the IndexError tell you the length of the sequence.  So it's not 
an exception fear, but a duplication of code fear, which I hope is somewhat 
more Pythonic. =)

It would have made describing the protocol somewhat more complex, but it would 
have made using the protocol in a class simpler.  Moot point of course, since 
I'm fully convinced that changing the protocol is infeasible. =)

Steve




More information about the Python-list mailing list