docs on for-loop with no __iter__?

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
 
T

Terry Reedy

Steven Bethard said:
Ahh, yeah, I'm sorry, I didn't even realize that reading of "always" was
possible. When I wrote "Same reasons Python always breaks old code" I
intended the reading "For the only reasons that Python ever breaks old
code",
but I can see the other reading now... Yup, I'll take my half. =)

I believe I also misread the same way Alex did, but other meaning now
clear.

tjr
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,771
Messages
2,569,587
Members
45,099
Latest member
AmbrosePri
Top