I'm working with a legacy system for which a Python interface has been added recently. In my code, I get messages containing ASCII strings for attributes to be set in some wrapper classes. I would like to use a dictionary to map "data labels" to property setter methods. Each property setter would be used as a "callback" when the corresponding data label is encountered in a message.
Using explicit setters/getters, the essential logic looks like this:
class A():
def __init__(self):
self._x = 1.2
def get_x(self):
return self._x
def set_x(self, value):
self._x = value
myA = A()
myTable = {
'X' : myA.set_x,
}
label, value = get_message()
print(myA.get_x())
# label is 'X', value a float
myTable[label](value)
print(myA.get_x())
This works, but is a bit ugly. I would like to use the @property
decorator, but then I don't know how to reference the setter method in the dictionary.
I.e. the following doesn't work.
class B():
def __init__(self):
self._x = 1.2
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
myB = B()
myTable = {
'X' : myB.x
}
label, value = get_message()
print(myB.x)
# doesn't work as expected
myTable[label] = value
# no change
print(myB.x)
Of course, the reference to property myB.x
in the dictionary definition calls the getter, so a float value is associated to the 'X' key. The myTable[label] = value
assignment just replaces this value, it doesn't call the setter.
So, is there a way to get a reference to the property setter to insert in the dictionary and to later invoke as a "callback"?
I dug in reference information and this answer, but can't figure out a solution by myself.
Or, am I getting it wrong and I should follow a different path? (Suggestions welcome).