I love the typing.NamedTuple
in Python 3.6. But there's often the case where the namedtuple
contains a non-hashable attribute and I want to use it as a dict
key or set
member. If it makes sense that a namedtuple
class uses object identity (id()
for __eq__
and __hash__
) then adding those methods to the class works fine.
However, I now have this pattern in my code in several places and I want to get rid of the boilerplate __eq__
and __hash__
method definitions. I know namedtuple
's are not regular classes and I haven't been able to figure out how to get this working.
Here's what I've tried:
from typing import NamedTuple
class ObjectIdentityMixin:
def __eq__(self, other):
return self is other
def __hash__(self):
return id(self)
class TestMixinFirst(ObjectIdentityMixin, NamedTuple):
a: int
print(TestMixinFirst(1) == TestMixinFirst(1)) # Prints True, so not using my __eq__
class TestMixinSecond(NamedTuple, ObjectIdentityMixin):
b: int
print(TestMixinSecond(2) == TestMixinSecond(2)) # Prints True as well
class ObjectIdentityNamedTuple(NamedTuple):
def __eq__(self, other):
return self is other
def __hash__(self):
return id(self)
class TestSuperclass(ObjectIdentityNamedTuple):
c: int
TestSuperclass(3)
"""
Traceback (most recent call last):
File "test.py", line 30, in <module>
TestSuperclass(3)
TypeError: __new__() takes 1 positional argument but 2 were given
"""
Is there a way I don't have to repeat these methods in each NamedTuple
that I need 'object identity' in?