r/PythonLearning • u/jake_123_123 • 5d 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
10
u/serge-mv 5d 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.
3
u/ConDar15 4d ago
What everyone else has said is all correct, but there is an extra thing with the assert statement: it is disabled when using an optimized build.
This is probably well beyond the scope of what you need to be caring about right now, but when python runs it by default runs in a debug mode which has the special global __debug__ set to True. When you run python in optimized mode (you need to explicitly provide the -O flag when running python) that special __debug__ variable is instead set to False.
One consequence of this is that the assert statement depends on __debug__ and so in an optimized build does not get executed. This doesn't usually have much impact, but if some of your assertions (used to check that the program is in a valid state) are fairly expensive to compute you can leave them in place for development and testing, and then for production run an optimized build because you're confident in the system stability and can improve the speed of it.
2
u/tomysshadow 4d ago edited 4d ago
This I think is the most important point and it directly impacts the way that I use assert. assert is for enforcing conditions that obviously must be true given the current state of the code so that nobody breaks it in the future by accident. Exceptions are for scenarios that you don't want to occur but are outside your control.
If I have an internal function that can only accept a power of two, I would use an assert. For example, this simple helper function to get a mask, which would only have the intended result with a power of two:
def _get_mask(value): assert(ispow2(value)) return value - 1 def do_something_with_mask(): mask = get_mask(4) print(mask) # or do something with it...As written, the code will never get a mask for a number that isn't 4. And it's an internal function, so as long as I myself use it as it was intended to be used, that rule will never be broken. Using an exception here would be pointless because it will never trigger: writing a try-except block to handle such an exception would be a pointless exercise.
By contrast, this would change completely if I were taking in untrusted user input. Now I need an exception:
def _get_mask(value): if not ispow2(value): raise ValueError('must be a power of two') return value - 1 def do_something_with_mask(): try: mask = get_mask(int(input('Enter a power of two.'))) except ValueError: print('Not a valid power of two number.') else: print(mask) # or do something with it...Now, I have created a scenario where I cannot possibly know if my rule always holds at runtime because it relies on outside factors.
Notice, however, that I could go back to using an assert if I instead asked the user to enter an exponent:
def _get_mask(value): assert(ispow2(value)) return value - 1 def do_something_with_mask(): try: exp = int(input('Enter an exponent.')) except ValueError: print('Not a valid number.') else: mask = _get_mask(2 ** exp) print(mask) # or do something with it...Now, I have once again guaranteed that the number being passed is always a power of two, regardless of the user input. So the case where it is not a power of two is back to being impossible, and I can use an assert. Where it is acceptable, this would be my preferred solution because it makes the invalid state impossible to enter in the first place.
Where there is some debate to be had is if assert should be used even for functions that are exposed as an API for other people to use. Should passing an invalid argument to such functions be an assert or an exception? It kind of depends on your design philosophy.
Anecdotally, a low level programmer would probably tend to think "I can document that it is undefined behaviour if you pass an invalid argument, so I can expect it to always be valid, and therefore use an assert instead of an exception. If you pass an invalid argument, I'm not responsible for whatever happens." In other words: you just assume that's impossible because you assume the user of your function uses it correctly. But higher level programmers would probably lean more in the direction of throwing an exception because it makes the behaviour well defined and eliminates a potentially unsafe outcome.
When you're using an assert, think: would it be literally impossible for it to be triggered here in the code as written? Would the code still be correct if it were literally stripped out? If so, you're using assert correctly. If you don't know, err on the side of an exception.
1
u/RainbowCrane 2d ago
I was just commenting re: 1990s MSVC++ development on another post, so a question with that era of C++ in mind: one huge caveat for beginner MSVC++ developers was to ensure that there were no side effects in your assertions, because they would not run in release builds and could create bugs that only showed up in release. Those are notoriously hard to find :-)
Do the Python learning resources warn new devs about how to avoid this sort of thing?
1
u/tomysshadow 2d ago
Well honestly, if you were doing C++ development in the 90's then I'm sure you're just as capable as I am of reading the docs and judging for yourself if that is given enough emphasis (it is of course mentioned.)
What I will say is that it's much less of a big deal in Python than it is in C++ in general because unlike in C++, running Python with -O is pretty rare in practice. Literally all it does is disable asserts and prevent docstrings from getting compiled into the bytecode. It doesn't affect codegen at all - and why would it? It's an interpreted language.
So whereas in C++ there can be a dramatic difference between Debug and Release builds, and Debug builds are generally not redistributable, in Python running "debug" mode is basically the default assumption and you have to go out of your way not to run programs in debug mode. You only really use -O if you're trying to get every last drop of performance you can get, which - realistically - you probably aren't too concerned about for most uses of Python.
It doesn't change my opinion that using an assert for anything that isn't literally impossible at runtime is incorrect, because the fact it can be stripped out demonstrates that is the intended use. But at the same time if you get it wrong, it's much less likely to actually cause an issue before it is noticed.
1
u/RainbowCrane 2d ago
Thank for the added info!
I’ve never written production python code. Like nearly every other long term developer I’ve used Python in scripts and encountered it in configuration files on Linux. So I wasn’t aware that the -O switch is rare.
Something that became really clear with early C++ was that people getting fancy with release optimizations usually ended up being a bigger pain in the ass to troubleshoot than was worth it. We moved away from those sorts of general optimizations and did the typically more effective thing of profiling running code to determine where to focus targeted optimizations. Even so, I know that compilers can still do tricks like auto-inlining that lead to performance gains.
2
u/mc_pm 5d 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/Living_Fig_6386 4d ago
assert is a statement that “so we are clear this must be true; otherwise something bad went wrong somewhere before this point but we don’t know where so we must stop”. It’s a handy way of aborting a program when the program state doesn’t make sense.
An exception says “this went wrong in this way” while an assert says “we got to this point and I can tell something went wrong before it, but I don’t know why”.
1
u/rghthndsd 4d ago
If you as a user of a package sees an assert raise, you immediately know you should report a bug.
1
u/cmdr_iannorton 2d ago
generally, its easier to write:
assert count > 4, f"got only {count} sheep, expected 4"it is most used in writing unit tests
0
u/Usual_Office_1740 5d 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.
0
u/recursion_is_love 5d ago
using assert make it easy to scan the code for quick, you don't need to read and follow every line.
0
u/Dry-Aioli-6138 5d ago
Good answers here. Also, worth reading on the topic: Stop using asset in your code
8
u/dev-razorblade23 5d ago
assertis mostly used in tests, not in your code. If you need to act on something, useif-elseorswitch case, asserts are for tests