A
Alex Martelli
Steven Bethard said: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.
If and only if __len__ is the ONLY sane way to tell, yes. Such cases
are exceedingly rare in practice, as you point out:
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): self.data = data
def __len__(self): return len(self.data)
def __getitem__(self, i):
try:
return self.data
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.
Right, except you don't have to intercept and reraise IndexError, just
let it propagate (if KeyError is meaningfully possible and excepted then
yes, you do have to catch and translate _that_ one).
Alex