docs on for-loop with no __iter__?

Steven Bethard steven.bethard at gmail.com
Mon Sep 6 17:36:36 EDT 2004


Alex Martelli <aleaxit <at> yahoo.com> writes:
> Consider __len__ used to be a popular way to let your instances be
> usable in a boolean context -- I believe __nonzero__ was introduced
> later.  So, take a class which only know whether it's empty or not, it
> could have a __len__ that only returns 0 (==empty) or  1(==nonempty),
> and still allow proper iteration by only raising in __getitem__ when all
> items have been iterated on.  If loops took account of __len__ suddenly
> all that old code would break.  Maybe there's much and maybe there's
> little, but why break ANY of it?!

Same reasons Python always breaks old code -- ease and clarity of coding.  
Hence the 'yield' keyword for generator functions, the change of method 
resolution order, etc.  Still, you make a good case -- I can imagine a fair 
number of classes might run into these bugs (as compared to a very few classes 
that would have changed from the introduction of 'yield' or the changed method 
resolution order).

> Just add MixinLenwiseIterator to your sequence classes' bases and be
> happy.

If you read my posts from the beginning, I was clearly never asking for the 
workaround -- I was asking for why the protocol was the way it was and why it 
hadn't been updated after __iter__ was introduced.  Despite a few snide 
remarks ;) you did answer my question though, thanks!

Anyone know if the __getitem__ protocol will still be supported in Python 3000?

Steve




More information about the Python-list mailing list