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

2 Upvotes

7 comments sorted by

•

u/norpadon 13m 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

•

u/jake_123_123 12m ago

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

•

u/Head_Mix_7931 9m ago

`assert not condition`

•

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

•

u/sweet-tom 10m ago

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

And if clause is never removed.

•

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

•

u/jcquarto 3m 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