10/31/2020

Can you write a Python program that will fail? I write code that fails nearly everytime I set out to write some kind of program. I would guess that there might be more ways to write a program that fails than there are to write a program that is successful. Most of the time the code I write will fail inadvertently, but recently I needed to write some simple code to test out my logic for fixing a production issue. It turns out to be pretty simple to write a program that fails in Python. For example, save the following code in a file named do_nothing.py and try running it.

import nothing


Assuming that you don't have any modules named "nothing", then you probably see some output like

Traceback (most recent call last):
File ".\do_nothing.py", line 1, in <module>
import nothing
ModuleNotFoundError: No module named 'nothing'


Now, suppose you have a function that processes some data in a loop, and then once the loop completes will output the final result of the data processing. Such a function might look like

def process():
value = 0
for i in range(10):
value += 1
print("The final value is {}".format(value))

process()


The result of running that program should be

The final value is 10


But what if that loop fails for some reason? How can we make it fail? Well, one way would be to import nothing inside of the loop.

def process():
value = 0
for i in range(10):
value += 1
import nothing
print("The final value is {}".format(value))

process()


Now running this program should give us this output:

Traceback (most recent call last):
File ".\do_nothing.py", line 8, in <module>
process()
File ".\do_nothing.py", line 5, in process
import nothing
ModuleNotFoundError: No module named 'nothing'


Hmm, well processing that value and getting it's final result is really important to us. Really, importing nothing is not so important, but we still want to give it a shot just in case it might succeed sometime. Let's utilize some exception handling to make this work better.

def process():
value = 0
for i in range(10):
value += 1
try:
import nothing
except Exception as e:
continue
print("The final value is {}".format(value))

process()


Now running that we get the output:

The final value is 10


Hooray! We got our important data by including a try/except block with a "continue" on an exception.

Knowing how to make Python "fail" like this and quickly implement your test logic is a great skill to have. It could make a difference in avoiding a failed loop that should be updating your database rather than sending thousands of *** URGENT *** emails to your boss during the night.

Happy hacking!