When should I use assert in a small Python program?
Quick answer
Use assert to check an internal assumption that should hold if your program’s logic is working. Don’t rely on it to validate user input or enforce any rule that must be checked on every run: Python may omit assertions when run with optimization (-O). For required checks, use an explicit condition and raise an appropriate exception instead. [S1]
The question, the details, the next step.
A practical checklist
Decide whether the condition must be checked on every run.
Validate outside values explicitly according to required rules.
Use
assertfor internal assumptions that should hold if your logic is correct.Do not make correctness depend on an assertion running.
Make failures understandable with an appropriate exception or a useful assertion message.
A few more useful answers
Can I use `assert` to check a command-line argument?
Not for a rule the program must enforce. Validate the argument explicitly and raise an appropriate exception; assertions may be omitted when Python runs with optimization. [S1]
What should I use an assertion for?
Use it to check an internal assumption that should hold if your program’s logic is working. It is a debugging check, not a required input-validation mechanism. [S1]
Should I replace every assertion with an exception?
No. Assertions can be useful for internal assumptions. Use an explicit condition and appropriate exception instead when the check represents a rule that must remain active on every run. [S1]
Sources
References used for this guide.
- [S1] Python Language Reference: The assert statement docs.python.org · Checked
