r/learnpython • • 7h 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

4 Upvotes

14 comments sorted by

9

u/norpadon 7h 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

2

u/jake_123_123 7h ago

ok, that makes more sense now. is there something like assert but for false statements? for something that should always be false ?

12

u/Head_Mix_7931 7h ago

`assert not condition`

•

u/Manostel-Jveive 5m ago

type checkers also read them to narrow down types for the rest of the scope, so you dont have to keep checking for None everywhere.

11

u/sweet-tom 7h ago

Asserts are removed when you optimize the Python code with the -O flag.

And if clause is never removed.

5

u/TheRNGuy 7h 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.

9

u/Major-Ad-4196 7h 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)

1

u/jcquarto 7h 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

4

u/davideogameman 7h 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/HummingHamster 6h 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 1h 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/dariusbiggs 7h 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

u/EnvironmentalDot9131 7h ago

The assert is done