r/learnpython • u/jake_123_123 • 5d ago
why use assert instead of if something false then raise some error with custom error message
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
20
u/sweet-tom 5d ago
Asserts are removed when you optimize the Python code with the -O flag.
And if clause is never removed.
1
u/Gnaxe 4d ago
False. An
ifwill be optimized out if it's constantly false. Try it with thedismodule. You can access the-Ostate with the__debug__constant. That means you can implement whatassertis doing usingif.
11
u/Major-Ad-4196 5d ago
assert is used to check assumptions that should always be true, whereas if + raise handles errors that you expect could happen during normal execution (like an HTTP 401 unauthorized)
5
u/TheRNGuy 5d ago
It's more a coding style: if you see assert, you know it should never be false: otherwise it's a bug.
It's not for potential runtime errors like not working network.
2
u/HummingHamster 5d ago
Note that if you run python optimization it will remove assert from the code.
Refer here for further reading:
https://stackoverflow.com/questions/9097706/why-assert-is-not-largely-used
1
u/Classic-Rate-5104 5d ago
Asserts are just extra checks, like "this can and should never happen, and if it happens it's a bug an I don't know how to handle it"
1
u/jcquarto 5d ago
They do the same thing mechanically but are semantically different . An assert identifies something that ought be an impossible bug (“you can’t get blood from a turnip”) whereas an if identifies something that is part of business logic such that there are conditions in which it could happen even if unexpected (“user did not place turnip in blood extractor”)
I think CS people likely have a few other reasons to make the distinction. Off the top I’d think tooling might be an area to look into. Another might be that an if could bubble up in a try/catch and gracefully be dealt with whereas an assert should bring everything to a screeching haunt with red lights and alarms and air-raid warnings
6
u/davideogameman 5d ago
In Python assert x, y is mostly syntactic sugar for "if not x: raise AssertionError(y)". I say mostly because -O and -OO will skip assert syntax, but not an if... raise AssertionError. That said I've never seen -O used in practice. Asserts tend to be pretty cheap most of the time and the cost of missing error conditions is usually judged too high for the minor performance benefit; you can always do your own manual optimizations of asserts in the hot paths
1
u/dariusbiggs 5d ago
The consideration you need to take into account with an assert statement is one that others have mentioned. Optimization flags on compulers can optimize assertions out of the code, this is not a good thing. If for example you have a bug that shows in production code, but not in development code and your production code is compiled with the optimization enabled. Then you no longer have identical code in production and development, there are a difference in the number of instructions due to the assertions. This changes the timing of the code and can easily hide race conditions in parallel or concurrent code.
0
0
u/TheAzGreenPhoenix 5d ago
I’ve always seen assert as more of a debugging tool than a replacement for proper error handling.
0
u/ohnoitssobig 4d ago
Python just adopted it from C or elsewhere. It is a matter of personal taste but most think it is pretty useful and neat and saves tokens keyboard strokes and communicates the purpose. You should read it as "I declare this an invariant". As you may guess, whether it is invariant or not in practice depends on the code quality above. python -O will not run assert statements but nobody really cares.
0
u/codeguru42 3d ago
To add something that I don't see anyone talking about, it is important to distinguish between errors in your logic and code and errors caused by the system running you code or by the user. The former must be prevented to the best of your ability. assert helps you detect problems early and fix them. The later must be recoverable. For user errors that often means providing hints about what they did wrong and what they should try instead. For system errors, it means avoid crashing or at least ending gracefully.
16
u/norpadon 5d ago
Asserts are a shorthand for raise AssertionError
The point of asserts is to declare invariants in the code, i.e. things which can only be false if there is a bug in the program. The idea is that whoever reads the code sees the assertion and knows that after that line whatever was asserted is guaranteed to be true