Reputation: 1772
I have a script that is operating a physical device. There is a physical malfunction on the device that occurs sometimes and when it does, I want to reset the device and continue with the script. I have this:
while True:
do_device_control()
device_status = get_device_status()
if device_status == 'Fault':
reset_device()
It seems to me that a neater / more Pythonic approach would raise an Exception:
try:
while True:
do_device_control()
device_status = get_device_status()
if device_status == 'Fault':
raise DeviceFaultException()
except DeviceFaultException:
reset_device()
But as far as I can see, there is no way to resume the script after resetting the device. Is there a way to make Exception handling work for this situation, or a more Pythonic approach than what I'm currently using?
Upvotes: 2
Views: 80
Reputation: 1014
A common Python idiom is "Ask forgiveness rather than permission", which applies very well to your question. An implementation like the following would suffice:
while True:
try:
do_device_control()
except DeviceFaultException:
reset_device()
This should get similar behavior as to what is in your original block of code using if statements.
However, you probably noticed that I did not check the device_status
in my code. This is because you should allow the do_device_control
function to raise the exception if it is unable to complete its task. This allows you to handle exceptions at the time the actions are being executed.
In an environment where you are working with a device that is running asynchronously to your code, you may check the device status and it be fine. It then might fail between the check and your do_device_control
function. This is one example of why the "ask forgiveness rather than permission" paradigm exists.
Of course, this example only works if you can expect the do_device_control
function to throw some sort of exception or change it so that it does. If you cannot expect/change this behavior, your first code block with the if statement would be preferred over explicitly raising an exception just to immediately catch it within the same code block.
Upvotes: 6