Python: Fail in three characters with 1/0

Here’s a code snippet I often type:
1/0
When this runs, Python raises ZeroDivisionError:
$ python -c '1/0'
Traceback (most recent call last):
File "<string>", line 1, in <module>
1/0
~^~
ZeroDivisionError: division by zero
I add such a “forced failure” to check if and when a line of code runs. It’s a quick-and-dirty way of answering questions like “is this function even called?” or “which tests run this block?”.
For example, I recently added 1/0 to a function that didn’t seem used and ran the test suite:
$ pytest
...
====================== short test summary info =======================
ERROR example/tests/test_widgets.py::RedWidgetTests::test_paint - ZeroDivisionError: division by zero
ERROR example/tests/test_views.py::FactoryViewTests::test_get - ZeroDivisionError: division by zero
ERROR example/tests/test_canteen.py::FoodTests::test_yumminess - ZeroDivisionError: division by zero
========================= 3 errors in 1.72s ==========================
The three errors’ stack traces showed me different code paths to the target function. I used this information when refactoring.
assert 0
If you want to be more “strict” about it, the shortest failing assert is:
assert 0
This is because 0 is falsey, so the assert will always fail. But I can’t be bothered to type this out during quick investigations.
KeyboardInterrupt for more power
The 1/0 technique doesn’t work if there is error handling that suppresses the exception, such as except Exception, or even the anti-pattern of a bare except. A more powerful but longer-to-type alternative is to raise KeyboardInterrupt:
raise KeyboardInterrupt()
This is the exception class that Python raises when interrupted with Control-C. It is very rarely suppressed.
Fin
I didn’t invent this technique, but I also can’t remember or find where I picked it up. Whoever told me about it, thank you!
To infinity and beyond,
—Adam
Learn how to make your tests run quickly in my book Speed Up Your Django Tests.
One summary email a week, no spam, I pinky promise.
Related posts:
Tags: python