[Python] How to use assert in Python production source code?

Discussão em 'Python' iniciado por Stack, Agosto 7, 2025.

  1. Stack

    Stack Membro Participativo

    We are looking at self-developed libraries shared between multiple Django projects or components of the same project, not the published open-source libraries.

    Question:

    We wonder whether it is OK to use assert to validate the variable's values.

    If yes, how?

    More information:

    1. An example of our idea:
      We are considering the example below that verifies the input logic equals to either and or or. And the design seems better than using a else clause assuming the value must be the other one.

    if logic == 'and':
    main_Q = main_Q & filter_Q
    elif logic == 'or':
    main_Q = main_Q | filter_Q
    else:
    assert False, "Invalid value of `logic`, it needs to be either `and` or `or`."


    Or:

    if logic == 'and':
    main_Q = main_Q & filter_Q
    else:
    assert logic == 'or'
    main_Q = main_Q | filter_Q

    1. We found usages of assert in the published open-source libraries.
      By doing a grep "assert" -v "test" to search in the site-packages directory, we found multiple assert statements in the functional source code, not for testing, in the libraries of amqp, argparse, billiard, celery, dateutil, decorator, distlib, etc. However, using assert seems to be an advanced technique, and we need help to find articles about the how-to's.

    ./amqp/sasl.py: assert isinstance(mechanism, bytes)
    ./amqp/sasl.py: assert isinstance(response, bytes)
    Binary file ./amqp/__pycache__/sasl.cpython-37.pyc matches
    ./argparse.py: assert self._current_indent >= 0, 'Indent decreased below 0.'
    ./argparse.py: assert ' '.join(opt_parts) == opt_usage
    ./argparse.py: assert ' '.join(pos_parts) == pos_usage
    ./argparse.py: assert action_tuples
    ./arrow-0.17.0.dist-info/LICENSE: incurred by, or claims asserted against, such Contributor by reason
    ./attr/_compat.py: raise AssertionError # pragma: no cover
    ./attr/_compat.py: raise AssertionError # pragma: no cover
    Binary file ./attr/__pycache__/_compat.cpython-37.pyc matches
    ./billiard/connection.py: assert waitres == WAIT_OBJECT_0
    ./billiard/connection.py: assert err == 0

    ... and many more matches ...


    1. We verified in test that the assertion fails only the one thread fulfilling the incoming HTTP request, and it does not fail the entire Django project. So, there is less worry about over-killing, but we also want to get confirmation.

    Continue reading...

Compartilhe esta Página