r/PythonLearning • • 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

4 comments sorted by

1

u/dev-razorblade23 3m ago

assert is mostly used in tests, not in your code. If you need to act on something, use if-else or switch case, asserts are for tests

1

u/jake_123_123 0m ago

i still don't get it. isn't the purpose of test to know exactly what failed and why? assert seems to defy this purpose by blindly giving errors. for example if i used it multiple times in one code i would not know which one failed exactly?

i am still learning, so i don't know if there are some ways that are just the conventional ways of testing?

1

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.