Beware of Python assertions in production code
Every now and then I see some code in a Python code base that uses assert
statements to verify preconditions. This is dangerous for a few reasons. The main one being that if the Python interpreter is run with certain flags assert statements are not executed. For this reason calling functions in python asserts can be dangerous as shown by this example:
count = 0
def counter():
global count
print("counter function called")
count += 1
return count
counter()
print(count)
assert counter() is not None
print(count)
$ python assertions_experiment.py
counter function called
1
counter function called
2
Running with the -O
optimize command line option:
$ python -O assertions_experiment.py
counter function called
1
1
It's worth noting that in all versions of Python assert
is a statement and not a function. This means you can't easily change this behaviour later like you can for example with print functions. By all means keep using assert
statements in your tests and perhaps in your prototypes but proceed with extreme caution in production code.