docs on for-loop with no __iter__?

Steven Bethard steven.bethard at
Tue Sep 7 19:23:32 CEST 2004

Alex Martelli <aleaxit <at>> writes:
> It's partly a matter of "look before you leap" versus "easier to ask
> forgiveness than permission", a conceptual distinction that IS quite a
> hobby-horse of mine (although "practicality beats purity", mind you.

Well, in either case, someone is looking before they leap.  If __len__ is 
checked in the protocol, then the protocol (i.e. the Python interpreter) has 
to do the looking.  Otherwise, the programmer has to do the looking to 
determine when to raise the IndexError.

Hmm...  Though I guess it kinda depends what you do in your __getitem__...  
The example we've been looking at was something like:

class S:
    def __len__(self): return 42
    def __getitem__(self, i):
        if 0 <= i < len(self):
            return i
        raise IndexError, i

So in this case, the programmer has to "look before they leap" (hence the if 
statement).  But in a more realistic situation, I can see that maybe you could 
just "ask forgivenesss instead of permission":

class T:
    def __init__(self, data): = data
    def __len__(self): return len(
    def __getitem__(self, i):
        except (IndexError, KeyError):
            raise IndexError, i

No look-ahead here -- assume you'll usually get valid indices and catch the 
exception if you don't.

More information about the Python-list mailing list