So your proposal is for assertions to stop being assertions?
Having assertions disappear when running under -O is fundamental to
what makes them assertions.
Assertions are not just a lazy coder’s way to check a condition and
raise an exception in one line. They are statements about code
correctness.
I think can I write out your pros and cons in two sentences:
Pros: lazy coders can feel good about writing lazy, misleading code that
raises an inappropriate exception when it fails.
Cons: assertions stop being assertions.
I have to say, that Twitter thread is painful to read.
- Yes, there are people who use assert to write assertions. I am one of
them. Grepping the stdlib would find 200+ examples, and a quick
spot-check suggests that they are being used correctly.
-
No, assert is not fragile if you use it for what it is intended for.
-
No, the caller of the code should (almost) never catch AssertionError.
(The rare exception is for code like error handlers that catches all
exceptions, logs them, and exits.)
- People who say that assertions are “plain wrong” outside of test
suites are “plain wrong”.
- If you are raising AssertionError for testing things which aren’t
assertions about your code’s correctness, e.g. for checking data
validity, you are doing it wrong. It is never appropriate to make
an assertion about external data, e.g. user-supplied data, arguments
passed to a public function by the caller, etc.
- If you actually expect that the assertion may be raised, and visible
to the caller, then AssertionError is almost certainly the wrong
exception to raise.
You wouldn’t write these validation tests for a public function:
if not isinstance(arg, int):
raise AssertionError('arg must be an int')
if arg <= 0:
raise AssertionError('arg must be greater than zero')
because they are the wrong exception class. So why would you use assert?
And you wouldn’t expect the caller to write this:
try:
value = data_table[index]
except AssertionError:
value = default
again, because it is the wrong exception for the error.
If you do expect the user to catch AssertionError, you should have a
long, hard look at your API.
Django devs: if you “worry” that users will run your code under -O and
disable your error checking code, then your code is broken.
Do C programmers abuse the assert macro like Python programmers abuse
assert? Are there masses of C programmers complaining that people can
turn off assertions from their code, or using it to perform data
validation?
https://ptolemy.berkeley.edu/~johnr/tutorials/assertions.html