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

10 Upvotes

20 comments sorted by

15

u/norpadon 4d 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

3

u/jake_123_123 4d ago

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

20

u/Head_Mix_7931 4d ago

`assert not condition`

1

u/GinormousBaguette 9h ago

someday one can hope to have lisp's (unless ...)

4

u/Manostel-Jveive 3d 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.

0

u/funkdefied 3d ago

Type checkers will also read ifs 

19

u/sweet-tom 4d ago

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

And if clause is never removed.

1

u/Gnaxe 3d ago

False. An if will be optimized out if it's constantly false. Try it with the dis module. You can access the -O state with the __debug__ constant. That means you can implement what assert is doing using if.

10

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

2

u/HummingHamster 4d 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

4

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

1

u/Classic-Rate-5104 4d 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 4d 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

5

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

The assert is done

0

u/TheAzGreenPhoenix 3d ago

I’ve always seen assert as more of a debugging tool than a replacement for proper error handling.

0

u/ohnoitssobig 3d 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 2d 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.