__eq__() inconvenience when subclassing set

Jess Austin jess.austin at gmail.com
Thu Oct 29 03:12:53 CET 2009

I'm subclassing set, and redefining __eq__().  I'd appreciate any
relevant advice.

>>> class mySet(set):
...     def __eq__(self, other):
...         print "called mySet.__eq__()!"
...         if isinstance(other, (set, frozenset)):
...             return True
...         return set.__eq__(self, other)

I stipulate that this is a weird thing to do, but this is a toy class
to avoid the lengthy definition of the class I actually want to
write.  Now I want the builtin set and frozenset types to use the new
__eq__() with mySet symmetrically.

>>> mySet() == set([1])
called mySet.__eq__()!
>>> mySet() == frozenset([1])
called mySet.__eq__()!
>>> set([1]) == mySet()
called mySet.__eq__()!
>>> frozenset([1]) == mySet()

frozenset doesn't use mySet.__eq__() because mySet is not a subclass
of frozenset as it is for set.  I've tried a number of techniques to
mitigate this issue. If I multiple-inherit from both set and
frozenset, I get the instance lay-out conflict error.  I have similar
problems setting mySet.__bases__ directly, and hacking mro() in a
metaclass.  So far nothing has worked.  If it matters, I'm using 2.6,
but I can change versions if it will help.

Should I give up on this, or is there something else I can try?  Keep
in mind, I must redefine __eq__(), and I'd like to be able to compare
instances of the class to both set and frozenset instances.


More information about the Python-list mailing list