DEV Community

Embrence
Embrence

Posted on

Should You Use assert in Python?

One of the more controversial Python discussions isn’t about frameworks or performance.

It’s about a single keyword:

assert

Some developers argue that assert should never be used.

Their reasoning is straightforward: assertions are removed when Python is run with optimization (python -O). If a check can disappear in production, they argue, it shouldn’t be responsible for enforcing important conditions.

Instead, they recommend explicit exceptions:

if age < 18:
raise ValueError("Age must be at least 18")

On the other hand, many experienced Python developers make a distinction between validating external input and checking internal assumptions.

For example:

assert user is not None

This isn’t validating user input.

It’s documenting an assumption that should already be true if the rest of the program is correct.

If the assertion fails, it usually indicates a bug in the program rather than invalid input from a user.

That’s why many developers use assert for debugging and internal invariants while relying on exceptions for runtime validation.

The important question isn’t:

“Should I always use assert?”

It’s:

“What am I trying to protect?”

If you’re validating user input, API responses, files, or anything that can legitimately fail during normal execution, exceptions are usually the appropriate choice.

If you’re checking assumptions that should never be false unless your own code contains a bug, an assertion can make that intent explicit.

In other words, assert and exceptions solve different problems.

What do you think?

Do you use assert in your projects, or do you prefer explicit exceptions everywhere?

Top comments (2)

Collapse
 
rondo profile image
Rondo

I agree with you. assert is for developers, not to validate data and user input.
Still, I personally prefer using if just because I am used to this 😂

Collapse
 
ldrscke profile image
Christian Ledermann • Edited

Another use I have for assert (very similar to your recommendation) is to make typecheckers happy. Mostly with:

assert something is not None
Enter fullscreen mode Exit fullscreen mode

Typecheckers pick easily up on this pattern and do not complain when you call something.attribute later in the code. When you use the if .. raise pattern the intent often gets missed.