__contains__ vs has_key() - am I missing a subtle distinction?

Skip Montanaro skip at pobox.com
Mon Oct 20 15:20:33 EDT 2003


I got to wondering if there is a difference between __contains__() and
has_key() for dictionaries (I don't think there is), so I peeked at
UserDict.UserDict and saw they were implemented as distinct methods:

    def has_key(self, key):
        return self.data.has_key(key)

    def __contains__(self, key):
        return key in self.data

even though the UserDict implementation explicitly defines self.data as a
true dict.  There can be no mistake what the semantics of the two methods
are.  I half expected __contains__ to be defined as

    __contains__ = has_key

Did I miss some subtle distinction or was the UserDict author just trying to
be as explicit as possible in demonstrating the relationship between methods
and language constructs?

Skip






More information about the Python-list mailing list