How does "for" work?
Aahz Maruch
aahz at panix.com
Tue Oct 10 14:43:33 EDT 2000
In article <Pine.SOL.3.96.1001010105911.8470C-100000 at condor.ee.washington.edu>,
Steve Juranich <sjuranic at condor.ee.washington.edu> wrote:
>
>In the list object, I have overridden __getitem__ to be the following:
>
>def __getitem__(self, key):
> return self.data[key]
Try this:
def __getitem__(self, key):
if not self.data.has_key[key]:
raise IndexError
return self.data[key]
The problem is that "for" wants an IndexError, not a KeyError. An
alternate implementation that's a bit faster (at the expense of some
clarity if one is not thinking Pythonically):
def __getitem__(self, key):
try:
return self.data[key]
except KeyError:
raise IndexError
--
--- Aahz (Copyright 2000 by aahz at pobox.com)
Androgynous poly kinky vanilla queer het <*> http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6
'Gender' isn't a definition, it's a heuristic. --Aahz
More information about the Python-list
mailing list