__contains__ vs. __getitem__

enigmadude at rock.com enigmadude at rock.com
Wed Aug 9 14:07:19 EDT 2006


That's a vague question, so the obligatory "it depends" response
applies here.

If you want to guard against the unexpected, perhaps it's a good idea
to write unit tests rather than to take someone's word that it *should*
work okay every time, in every case, no matter what you're doing with
the data. Think of what behavior would be disasterous (whether it seems
possible or not), then write a test for that behavior. Also write tests
for things that "obviously" *should* hold true... just to make sure
they hold true.

Maybe you can't think of ways that this class could possibly screw
things up, but it's always nice to have reassurance anyway :-) The
closest thing to certainty about code is to test it.

David Isaac wrote:
> I have a subclass of dict where __getitem__ returns None rather than
> raising KeyError for missing keys.  (The why of that is not important for
> this question.)
>
> I was delighted to find that __contains__ still works as before
> after overriding __getitem__.    So even though instance['key']
> does not raise KeyError, I still get (as desired)  'key' in instance ==
> False.
>
> Looking forward:
> Can I count on this independence of __getitem__ and __contains__?
> I would like to understand whether it will be safe to count on this
> behavior.
> 
> Thank you,
> Alan Isaac




More information about the Python-list mailing list