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

5 Upvotes

27 comments sorted by

8

u/dev-razorblade23 4d 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 4d 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?

6

u/dev-razorblade23 4d 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.

1

u/Fun_Army2398 4d ago

It sounds like you don't know that you can pass custom messages to assert. Try something like:

assert False, "this is an example"

You're right in that this could also be done with:

if True: raise Exception("this is an example")

The difference is that an assertion should never fail. It has no support for error handling because it's supposed to crash your program. They're mostly used in testing and as such testing plugins and libraries are built with assertions in mind. Exceptions are used to keep your program running when some error occurs. It can be caught in a try except block and handled.

0

u/jake_123_123 4d ago

thanks, that is helpful. yes I didn't know i could do that

2

u/RedAndBlack1832 4d ago

By most testing convention you compute some result and then assert that it's the value you would expect if the program were working correctly. Like if I was computing a square root I might `result = func(4); assert result == 2`. You might also assert the correct kind of exception was thrown by asserting `isinstance` or something similar (though there are also wrappers for this in good testing frameworks)

1

u/arivictor 4d ago

Its not just for tests. It can be used for debugging and programmer errors, like things that should NEVER happen from a programmers perspective, not error handling user input.

Example.

# math.py

def add(a: int, b: int) -> int:
  assert(type(a) == int), "type(a) was not an int"
  assert(type(b) == int), "type(b) was not an int"

  return a + b

def run():
  # some dev config, not user input
  a = 15.0
  b = 2
  add(a, b)

We want the above to fail hard because of a programmer error. The dev provided the wrong configuration.

Why not just use if/raise-exception? I hear you ask..

Well, you can, it just depends what angle you're looking at it from.

def add(a: int, b: int) -> int:
  if type(a) != int:
    raise Exception("type(a) was not an int")
  if type(b) != int:
    raise Exception("type(b) was not an int")

  return int(a + b)

def run():
  a = handle_user_request()
  b = handle_another_user_request()
  
  try:
    add(a, b)
  except Exception as e:
    # handle the error caused by the user here
    print(e)

This communicates that mismatched types are an anticipated error that must be handled at runtime. Whereas assert we're checking during development time, we would NEVER expect those to execute in production.

2

u/sausix 3d ago

Type hints can be narrowed with assertions too. Happens sometimes and then you assert the type checker a certain type or else the program would have "crashed".

1

u/paperic 3d ago edited 3d ago

People here are confusing test assertions with the actual assert you're talking about.

The classical assert, the one that blows your program up if the condition is false, the main purpose of it is to blow your program up when the condition is false. That's it.

It's the software equivalent of the Big Red OFF button for safety.

It's also made to be as foolproof and simple to use as possible, which is why it's prefered over conditional throw in these situations. It's used when you really need to trust your code.

It's not meant for any kind of conceivable situations that are vaguely predictable or expected, like the user entering emojis as their age, or the program not having permissions to write to a file.

It's meant for inconceivable situations:

b = a + 1

assert (a == b - 1), "Math is broken"

If we know that a is an integer then there is no possible way for this to ever fail.

...unless your CPU is malfunctioning, you have a memory corruption, a compiler error, or some floating point nonsense is happening with numbers which, to your absolute best knowledge, can never ever be anything else except integers.

Assert is there to express all those assumptions upon which everything else relies on. You'd only ever assert the statements which you 100% know must be always true.

Because even if the hardware is working perfectly, we are all humans, we all make mistakes, and some day, one of those asserts will fail.

When that happens, the program will be in an inconceivable state, which you, as the programmer, previously considered entirely impossible. Therefore, there's no possible way to predict what the program is going to do next, and it's virtually guaranteed that killing it ASAP is better than letting the program run and do something random and unpredictable.

This is especially important if your program runs in some high stakes environment.

If your program controls a radiation therapy machine, or some large assembly line robot, or a self driving car, you may want to have more assert statements than regular code.

1

u/Scared-Letterhead949 2d ago

It tells you what went wrong.  Line 99 assert failed true is not false.

1

u/codeguru42 1d ago

No assert isn't blind. It only gives an error when the condition fails. pytrst uses it extensively.

1

u/codeguru42 1d ago

assert throws and exception when the condition fails. This includes a stacktrace showing the exact line just like any other exception. So no, you don't have to guess which of 30 asserts in your code failed. Also assert takes and optional string argument that customizes the error mrssage

1

u/La-ze 13h ago

It conditionally gives errors, not blindly. When an assert fires you should have a stack trace that tells you the exact line, all the function calls leading up to it and the frame information.

9

u/serge-mv 4d 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 3d 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 3d ago edited 3d 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 1d 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 1d 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 23h 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 4d 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 3d 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 3d ago

If you as a user of a package sees an assert raise, you immediately know you should report a bug.

1

u/billsil 3d ago

assert x> 0, ‘bad x’ tells me about the why, so I can be lazier

assert area > 0, area is even lazier. I absolutely use asserts in production. Do some type checking. Don’t ever send me bad data, but since I don’t trust myself, yeah throw a blanket catch all errors and log them.

1

u/cmdr_iannorton 1d 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 4d 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 4d 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 4d ago

Good answers here. Also, worth reading on the topic: Stop using asset in your code