Is there a performance or code maintenance issue with using assert
as part of the standard code instead of using it just for debugging purposes?
Is
assert x >= 0, 'x is less than zero'
better or worse than
if x < 0: raise Exception, 'x is less than zero'
Also, is there any way to set a business rule like if x < 0 raise error
that is always checked without the try/except/finally
so, if at anytime throughout the code x
is less than 0 an error is raised, like if you set assert x < 0
at the start of a function, anywhere within the function where x
becomes less then 0 an exception is raised?
Yes it is a very good practice to assert your assumptions. Read Design By Contract. assert can be used to verify pre conditions, invariants and post conditions during integration and testing phases. This helps to catch the errors while in development and testing phases.
To properly use assertions as a debugging tool, you shouldn't use try … except blocks that catch and handle AssertionError exceptions. If an assertion fails, then your program should crash because a condition that was supposed to be true became false.
You can use an assert to check if your logical assumption is correct. You can also use assert statements to check if the control flow is correct or not. For example, if you have a function that returns a value, you may want to put an assert statement. However, you may get a 'non-reachable' code error.
Keep in mind that assert is not meant to prevent errors from happening in runtime and as such, should not be used to perform data validation. Moreover, never use parentheses between the condition and the error message since Python always evaluates tuples to True and the assertion will never fail.
Asserts should be used to test conditions that should never happen. The purpose is to crash early in the case of a corrupt program state.
Exceptions should be used for errors that can conceivably happen, and you should almost always create your own Exception classes.
For example, if you're writing a function to read from a configuration file into a dict
, improper formatting in the file should raise a ConfigurationSyntaxError
, while you can assert
that you're not about to return None
.
In your example, if x
is a value set via a user interface or from an external source, an exception is best.
If x
is only set by your own code in the same program, go with an assertion.
"assert" statements are removed when the compilation is optimized. So, yes, there are both performance and functional differences.
The current code generator emits no code for an assert statement when optimization is requested at compile time. - Python 2 Docs Python 3 Docs
If you use assert
to implement application functionality, then optimize the deployment to production, you will be plagued by "but-it-works-in-dev" defects.
See PYTHONOPTIMIZE and -O -OO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With