I'm creating some Python code that reads values from a hardware device. This means, the code only works when the hardware device is attached but I'd like to increase the testability of the code and simulate the hardware output in case the code is running somewhere else (e.g. in a test environment/pipeline).
In my current code a debug flag is used as well as a generator that produces dummy data. If the debug flag is set to true, the data generator is called, otherwise the real hardware data is returned like so:
class Test():
def __init__(self, debug=False, data_generator=None):
self.debug = debug
self.data_generator = data_generator
def read_from_hardware(self):
if self.debug is False:
# code that calls the hardware device
else:
return next(self.data_generator)
# there are more methods that interact with the hardware
What I dislike in this code is that every method that has a hardware dependency uses the if/else statement on top. Is there a cleaner solution for this scenario? I was thinking of something like the following pseudo code but I'm not sure if 1) this is really a better approach and 2) if methods can be overloaded based on an instance variable value easily in Python.
class Test():
def __init__(self, debug=False, data_generator=None):
self.debug = debug
self.data_generator = data_generator
def read_from_hardware(self):
# code that calls the hardware device
@debug
def read_from_hardware(self):
return next(self.data_generator)