Skip to content Skip to sidebar Skip to footer

Unexpected Behavior For Python Set.__contains__

Borrowing the documentation from the __contains__ documentation print set.__contains__.__doc__ x.__contains__(y) <==> y in x. This seems to work fine for primitive objects s

Solution 1:

For sets and dicts, you need to define __hash__. Any two objects that are equal should hash the same in order to get consistent / expected behavior in sets and dicts.

I would reccomend using a _key method, and then just referencing that anywhere you need the part of the item to compare, just as you call __eq__ from __ne__ instead of reimplementing it:

classCA(object):
  def__init__(self,name):
    self.name = name

  def_key(self):
    returntype(self), self.name

  def__hash__(self):
    returnhash(self._key())

  def__eq__(self,other):
    if self._key() == other._key():
      returnTruereturnFalsedef__ne__(self,other):
    returnnot self.__eq__(other)

Solution 2:

This is because CA doesn't implement __hash__

A sensible implementation would be:

def__hash__(self):
    returnhash(self.name)

Solution 3:

A sethashes it's elements to allow a fast lookup. You have to overwrite the __hash__ method so that a element can be found:

classCA(object):
  def__hash__(self):
    returnhash(self.name)

Lists don't use hashing, but compare each element like your for loop does.

Post a Comment for "Unexpected Behavior For Python Set.__contains__"