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

S

Skip Montanaro

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
 
A

Alex Martelli

Skip said:
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?

I suspect the latter. There are no differences now, and I don't think
any were ever planned from back when __contains__ was introduced. But
asking on python-dev may give you a better chance to hear from the
original author.


Alex
 

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

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top