Python can we use `assert` key word in production code

Hello - A quick question assert key word can we use production code.

thanks

We can use assert in production code but it’s generally frowned upon. You are much better served by checking the value is what is expected and raising the correct Exception if it’s not. It will make handling the issue much simpler.
As a general rule we only assert in tests.

2 Likes

How would you handle all these AssertionErrors?

This is a decision your organization makes, not folks on a forum. You can do whatever you like.

One detail to keep in mind[1]: assert statements are not evaluated when Python is run with option -O or -OO. If you’re using one of those options in production, you shouldn’t rely on asserts to do anything.


  1. maybe this is what you are asking, but I don’t know ↩︎

7 Likes

Okay, Thank you!

It will handling by global exception handler which we implemented.

This isn’t how exceptions should be used. Sure, you can use a global bare except at the root of the call tree as a safety net.

Exceptions should always be handled where they’re expected to occur.

2 Likes

Exceptions should be handled where you can actually handle them. Otherwise, a global handler (possibly the default one) is the best. Do NOT get into the habit of “an exception could happen, so I have to catch it”.

3 Likes

With that, if you can reasonably expect an Exception to happen someplace specific in your code you are better off trying to handle it where it occurs. I would much rather catch the exception of trying to convert a non-numeric string into an int or a float where it happens so I can handle it appropriately.

1 Like

If you are getting AssertionErrors, something is horribly wrong, and you should fix your code. You do NOT write code to catch AssertionError unless it’s part of a test suite or similar. An assertion is something that, according to the code itself, should always be true; so if it isn’t, there is a bug. Let that exception go all the way to a global handler, possibly terminating the app.

The correct way to use assertions is as checked comments.

def build_border(text):
    if len(text) > MAX_WIDTH - 4: raise ValueError("Text too wide")
    line = "| " + text + " |"
    assert len(line) <= MAX_WIDTH
    print("=" * len(line))
    print(line)
    print("=" * len(line))

The assertion cannot ever be false if the code above it is bug-free. Other checks are done with simple “if: raise” and use a more appropriate exception.

An assertion error coming out of this code clearly indicates a bug. The checks can be skipped if you don’t feel the need to verify, or reenabled at any time with [1] no risk (other than performance).

So yes, you absolutely can use assert in production. Its job is to get out of the way when you turn on optimizations, but to never trigger unless something is very definitely wrong.


  1. theoretically ↩︎

4 Likes

Is that where you can handle it? Then yes, handle it there.

This has nothing to do with how close it is to where it “occurs”, which might not be where you think it is. There could be many layers between you and the spawning of the exception, but at the point where you have an option of doing something else with the failure, that’s where you catch it.

1 Like

I just looked up what production code means, and most sources emphasize that it is code that has been fully tested and is intended to be stable and reliable in a live environment. If a piece of code running in production consistently fails due to bugs, that suggests it may not meet the standards of production code, even though it is being used in production.

You can test or experiment with code while it’s in use, but unless it’s fully vetted and trusted, it’s more accurate to call it ‘code used in production,’ not true ‘production code.’

If the intent is to do live testing, then it’s fine to use asserts.

1 Like

Fact of life: even production code isn’t bug-free.

Assertions exist so that you can have a low-cost way to verify things - low-cost because they can easily be removed by simply running Python in optimized mode.

Are you suggesting that “production code” has to be bug-free? If so, the only thing ANYONE has EVER used is “code used in production”.

4 Likes