I think this will be most easily demonstrated with an example, but the question is a general one. Say I am using a library like PyVISA, which interfaces GPIB devices with my program. I have set up a python class for each instrument, so for a power supply, I might have something like this:
import visa
class PowerSupply:
def __init__(self):
rm = visa.ResourceManager()
self.ps = rm.open_resource('GPIB0::12::INSTR')
def getVoltage(self):
return self.ps.ask('VOLT?')
def setVoltage(self,v):
self.ps.write('VOLT '+str(v))
...
ps = PowerSupply()
ps.setVoltage(10)
Unfortunately, there is the chance that the rm.open_resource
function may not work, or might return None
if a device does not exist at that address (in my code I actually wrote a function that did this instead). My question is: what is the best practice for coding a class like PowerSupply
? One could write exceptions into every method that test if self.ps
exists/is not None
, but it seems there must be a better way. Is there?!