Search code examples
pythonequalitymixins

python valuetype hash mixin


In Python, I often find myself having to override equality and hashing for classes where the equality should be based on a particular piece of data. I usually end up abstracting this to a superclass like this, but I was wondering if Python has anything like this built in. It seems like a common task.

class ValueType(object):
    def __init__(self, *args, **kwargs): super(ValueType, self).__init__(*args, **kwargs)
    def __eq__(self, other): return self._key() == other._key()
    def __ne__(self, other): return self._key() != other._key()
    def __hash__(self): return hash(self._key())    

Solution

  • The answer, as far as I know is no, (based off two years of using Python) but that's hardly proof.

    Practically though, I'm not sure I would use a ABC like you have there. It's probably makes more sense to use it as a mixin, letting you clearnly remove the init. Python doesn't explicitly support mixins, but it supports multiple inheritance so it's trivial to implement. Assuming there is agreement, you'll want to look up Python Method Resolution Order (MRO) and make sure you order your classes right. (In this case, ValueType should be before object.)