I’m learning to write classes in python and am trying to understand better default actions:
In particular, I’m working on a class for set of instruments. It turns out that this class of instruments has a help message that documents the full command interface, and the structure of this help is the same for all instruments from that manufacturer (“Windfreak Tech”, cool USB microwave generators and up/down converters).
My idea is that rather than hardcoding the parameters of the class, I can parse them from the help message into a dictionary. So my class has basically just a dictionary with entries like:
wft.value["Frequency (MHz)"]
I would like be able to type something like this:
wft.value["Frequency (MHz)"] = 1000.3
and then have this automatically run the write() code to set this value (and query it back maybe).
As I’m new to using observer properties in python, I was wondering: what is the best way to do this? I would somehow need to pass both the key and the value to my setter function?
Instead of storing this information in a barebones dictionary, you can implement your custom container that executes the necessary code when modified. An observer pattern is more complex.
Here’s how it could work.
class VerboseDict(dict):
def __setitem__(self, key, value):
print(f"Setting {key} to {value}")
# Call the dictionary method using the super built-in
super().__setitem__(key, value)
def __getitem__(self, key):
print(f"You have requested {key}, here you go.")
return super().__getitem__(key)
data = VerboseDict()
data["Frequency"] = 100
print(data['Frequency'])
prints
Setting Frequency to 100
You have requested Frequency, here you go.
100
(as I was writing my post I was already thinking something like that might be best …sometimes just formulating the question you come up with the answer…)