Creating a namedtuple with a custom hash function
I think there is something wrong with your code (my guess is that you created an instance of the tuple with the same name, so fooTuple
is now a tuple, not a tuple class), because subclassing the named tuple like that should work. Anyway, you don't need to redefine the constructor. You can just add the hash function:
In [1]: from collections import namedtuple
In [2]: Foo = namedtuple('Foo', ['item1', 'item2'], verbose=False)
In [3]: class ExtendedFoo(Foo):
...: def __hash__(self):
...: return hash(self.item1) * hash(self.item2)
...:
In [4]: foo = ExtendedFoo(1, 2)
In [5]: hash(foo)
Out[5]: 2
Starting in Python 3.6.1, this can be achieved more cleanly with the typing.NamedTuple
class (as long as you are OK with type hints):
from typing import NamedTuple, Any
class FooTuple(NamedTuple):
item1: Any
item2: Any
def __hash__(self):
return hash(self.item1) * hash(self.item2)