0

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
asked Apr 13, 2021 at 14:23

1 Answer 1

0

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.

answered Apr 13, 2021 at 14:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.