r/PythonLearning • u/jake_123_123 • 44m 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
2
u/serge-mv 39m 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 36m 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.
1
u/mc_pm 11m ago
Assert is for stuff that *must* be true, and where you are saying right from the code level "this indicates something is really wrong".
An exception is more about an expectation that wasn't fulfilled: the file doesn't exist, you ended up dividing by zero, the network connection couldn't be established, etc. These aren't normal problems, but they are 'expected' and you can plan for. If you put something in assert you're saying "that's it, fail out right now, the system isn't in a state I can continue with".
1
u/dev-razorblade23 38m ago
assertis mostly used in tests, not in your code. If you need to act on something, useif-elseorswitch case, asserts are for tests