Python 3 assert statements

Revision history
Tags: python

The syntax is a bit different from standard Python functions, as there are no parens () here.

assert <expression1>[, <expression2>]

The basics are

I am testing to see if this is a good way to assert expectations during normal program execution.

try:
    assert shouldProcess
    assert len(address) > 0, "Address is required"
    assert type(zip) is num, "Zip code is not a number"
    assert valid_users.get(name) is not None, "User does not exist"
except AssertionError as e:
    logging.error(e)

Note that assertion statements will not run when Python optimisation flag is enabled. I.e. python -O or PYTHONOPTIMIZE=1, so it might be safer to go about this in a different way for my example use-case.

References

If you have any comments or feedback, please send me an e-mail. (stig at stigok dotcom).

Did you find any typos, incorrect information, or have something to add? Then please propose a change to this post.

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.