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

1 Upvotes

6 comments sorted by

1

u/dev-razorblade23 38m 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 35m 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/dev-razorblade23 28m ago

No, the purpose of tests is to make sure your previus code does not break when you implement new stuff.

You write tests separate from your code. And you execute those tests before you ship it. They guard your code from regression bugs and makes sure that is doing what its supposed to do.

If you are still learning, skip assert for now, use if-else blocks in code. Once you start actually writing tests, you will see the benefits.

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".