Tag Archives: debugging

Python’s assert statement

Python’s assert statement asserts that a value is True. If the value is not True, an AssertionError is raised.

Consider the following code.

assert True
assert False

The first line basically does nothing because the argument to assert is True. The second line will throw an AssertionError.

The assert statement is useful for explaining code. Let’s say I wrote a piece of code to explain how to add numbers in Python.

sum = 2 + 2
assert sum == 4

The assert line asserts that the variable sum must equal 4 – otherwise the code wouldn’t work. Without assert, the above code would have to be written like this.

sum = 2 + 2
# sum now equals 4

Having the assert statement makes it a little more eloquent to write about code.

Rubber Duck Debugging

Today I helped a colleague solve an issue she was having simply by listening. By giving her an opportunity to discuss the topic with me, she was able to work out the solution herself. Before I had even fully understood the problem, she thanked me for the help.

This technique of problem solving even has a name: “Rubber Duck Debugging“. The term comes from a story in the book The Pragmatic Programmer.

The idea is to obtain a rubber ducky, keep it at your desk, and explain your code
to it whenever you are stuck on a problem – though you can use a human in place of the duck, if you prefer. The human doesn’t need to programmer. The technique is based on the idea that teaching a subject forces an evaluation from a different perspective allowing for a deeper insight into the problem.