brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python -O removes assert statements, so never use them for real checks

Python
~/tips/tip-python-o-strips-assert

python3 -O check.py # assert is skipped, delete_everything() runs

Know when assert disappears and what to use for checks that must always run.

assert is great for catching your own mistakes while developing. It’s not a safe way to check input, because one flag makes every assert vanish.

cat check.py
# assert user.is_admin, "not allowed"
# delete_everything()

python3 check.py      # AssertionError: not allowed
python3 -O check.py   # assert is skipped, delete_everything() runs

With -O, or with PYTHONOPTIMIZE set in the environment, Python compiles the code as if every assert line wasn’t there. The constant __debug__ becomes False as well. Nobody tells you; the program just runs on.

So the rule I’d follow: assert is for things that can only be false when your own code has a bug, like an internal list that should never be empty. Anything that depends on the outside world, such as user input, permissions, config values or a file that may be missing, gets a normal if with a raise:

if not user.is_admin:
    raise PermissionError("not allowed")

Most people never run Python with -O, which is exactly why this bites. Somebody adds PYTHONOPTIMIZE=1 to a container image to save a little startup time, and the checks are silently gone in production.

Further reading: The assert statement, python -O

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link