r/PythonLearning • u/jake_123_123 • 10m ago
Discussion why would you use assert instead of if false: raise someerror("custom message about error"). what are the benifits of assert. because it seems that it doesn't save time nor effort, nor does it communicate code better than an if with custom error message
1
Upvotes
1
u/dev-razorblade23 3m ago
assertis mostly used in tests, not in your code. If you need to act on something, useif-elseorswitch case, asserts are for tests1
u/serge-mv 4m ago
They serve different purpose. Assert is for a condition that should never be false. If assert fails, you have a bug or a catastrophic failure. if-statement is simply for different paths a code can take. Everything inside if is expected and normal. Normally you would not use asserts in production, but in tests while if-statements is a normal statement you use in code.
1
u/Usual_Office_1740 1m ago
For me it's about conveying intent. In basic general terms, an error is a problem to be handled someplace other than the site it's raised from. An assert is something that should never actually happen. If it does happen crash so I can use a debugger to know when, where, why and how.