Hashability questions

Christian Heimes lists at cheimes.de
Mon May 14 21:50:27 EDT 2012


Am 13.05.2012 21:11, schrieb Bob Grommes:
> Noob alert: writing my first Python class library.
> 
> I have a straightforward class called Utility that lives in Utility.py.
> 
> I'm trying to get a handle on best practices for fleshing out a library.  As such, I've done the following for starters:
> 
>   def __str__(self):
>     return str(type(self))
> 
> #  def __eq__(self,other):
> #    return hash(self) == hash(other)
> 
> The commented-out method is what I'm questioning.  As-is, I can do the following from my test harness:

By the way, that's a dangerous and broken way to implement __eq__(). You
mustn't rely on hash() in __eq__() if you want to use your object in
sets and dicts. You must implement __hash__ and __eq__ in a way that
takes all relevant attributes into account. The attributes must be read
only, otherwise you are going to break sets and dicts.

Here is a best practice example:

class Example(object):
    def __init__(self, attr1, attr2):
        self._attr1 = attr1
        self._attr2 = attr2

    @property
    def attr1(self):
        return self._attr1

    @property
    def attr2(self):
        return self._attr2

    def __eq__(self, other):
        if not isinstance(other, Example):
            return NotImplemented
        return (self._attr1 == other._attr1
                and self._attr2 == other._attr2)

    def __hash__(self):
        return hash((self._attr1, self._attr2))

    # optional
    def __ne__(self, other):
        if not isinstance(other, Example):
            return NotImplemented
        return not self == other









More information about the Python-list mailing list