This is a revised version of the code from the previous question. It corrects the spelling errors, add in appropriate comments for argument types and doc strings, rewrite number representation, and make the code reproducible by adding in the fake device yaml file. It will be great to get a review how I can improve the code further.
import pyvisa_sim
import pyvisa
# Method 1
class Instrument1():
""" Instrument1 uses getter and setter method. """
def __init__(self, rsc_addr, rm):
self._rm = pyvisa.ResourceManager(rm)
self._rm.timeout = 25e+03
self.instr = self._rm.open_resource(rsc_addr, read_termination='\n', write_termination='\n')
def get_freq(self) -> float:
""" Get the instrument frequency. """
return self.instr.query("freq?")
def set_freq(self, freq: float) -> None:
""" Set the instrument frequency. """
self.instr.write(f"freq {freq}Hz")
# Method 2
class Instrument2():
""" Instrument2 uses property method. """
def __init__(self, rsc_addr, rm):
self._rm = pyvisa.ResourceManager(rm)
self._rm.timeout = 25e+03
self.instr = self._rm.open_resource(rsc_addr, read_termination='\n', write_termination='\n')
@property
def freq(self) -> float:
""" Get the instrument frequency. """
return self.instr.query("freq?")
@freq.setter
def freq(self, freq: float) -> None:
""" Set the instrument frequency. """
self.instr.write(f"freq {freq}Hz")
def main():
# path to fake object yaml file
sim_fpath = 'sim_dev.yaml@sim'
freq = 150e+09 # 150GHz
rm = pyvisa.ResourceManager(sim_fpath)
# use the first resource that can be found
addr = rm.list_resources()[0]
inst1 = Instrument1(rsc_addr=addr,rm=sim_fpath)
inst1.set_freq(freq)
f1 = inst1.get_freq()
print(f1) # this should print out 150e+09
inst2 = Instrument2(rsc_addr=addr,rm=sim_fpath)
inst2.freq = freq
f2 = inst2.freq
print(f2) # this should print out 150e+09
if __name__ == "__main__":
main()
sim_dev.yaml file for fake instrument
spec: "1.0"
# devices' specification
devices:
device 1:
eom:
GPIB INSTR:
q: "\n"
r: "\n"
error: ERROR
dialogues:
- q: "*IDN?"
r: "PyOctal,SIM,MOCK,VERSION_1.0"
properties:
freq:
default: 100.0e+09
setter:
q: "freq {:.2f}Hz"
getter:
q: "freq?"
r: "{:.2f}"
# different usable resources
resources:
GPIB::0::INSTR:
device: device 1
_rm
"private" (because of the leading underscore in its name) but attributeinstr
isn't? 2. Is theimport pyvisa_sim
statement necessary? \$\endgroup\$