IndexError and for x in list
Niels Diepeveen
niels at endea.demon.nl
Fri Apr 14 11:25:52 EDT 2000
"Michal Wallace (sabren)" schreef:
> def _toStringKey(self, key):
> """Convert numeric keys into string keys. Leaves string keys as is"""
> # handle numeric keys:
> if _isNum(key):
> if not (0 <= key < len(self.idx)):
> ## oddly enough, it is this IndexError here
> ## that allows you to do "for x in myIdxDict:"
> raise IndexError, `key` + " is out of bounds."
> # convert it to a string key
> key = self.idx[key]
>
> return key
Or, a bit simpler:
def _toStringKey(self, key):
"""Convert numeric keys into string keys. Leaves string keys as
is"""
# note that sequence indexes must be integers
if type(key) is type(0): # note that sequence indexes must be
integers
return self.idx[key] # this will raise the IndexError when
needed
else:
return key
> Basically, I don't want to rely on an undocumented feature that could
> go away sometime. Is IndexError the right way to simulate a list?
If you take the above approach, that problem will go away, since you
will simply pass on the error handling of a real list, whatever that may
be. To be on the safe side, you might also implement __len__ if that
isn't already done. That should take care of any alternative
implementation of 'for' that I can imagine. If you really want to do
everything a list can do, read 'Emulating sequence and mapping types' in
the language reference.
--
Niels Diepeveen
Endea automatisering
More information about the Python-list
mailing list