I'm trying to update a key from a python object via a subscriber/pattern, this is part of a larger code base but I would like to check if I'm doing something wrong here.
from dataclasses import dataclass
@dataclass
class A:
a:float=2
def mod(self,name):
self.a = name
def __hash__(self):
return hash(self.a)
class B:
x = {}
def attach(self,object):
self.x[object]= getattr(object,'mod')
def dispatch(self):
for _, val in self.x.items():
val(3)
When executing
>>>a = A()
>>>b = B()
>>>print(a.a)
>>>b.attach(a)
>>>print(b.x)
As expected:
{A(a=2): <bound method A.mod of A(a=2)>}
>>>print(b.x[a])
<bound method A.mod of A(a=2)>
Then when executing the update
>>b.dispatch()
>>print(b.x)
{A(a=3): <bound method A.mod of A(a=3)>}
But when the key is verified:
>>>print(list(b.x.keys())[0] is a)
True
When trying to retrieve the method
>>>print(b.x.get(a))
None
1 Answer 1
Apparently the problem comes from the way hash is defined. Hashing should respect some properties. Dictionaries require hashable keys according to link
From the Official documentation
Having a hash() implies that instances of the class are immutable. Mutability is a complicated property that depends on the programmer’s intent, the existence and behavior of eq(), and the values of the eq and frozen flags in the dataclass() decorator.
Explore related questions
See similar questions with these tags.