safe-assert

raw JSON →
0.5.0 verified Fri May 01 auth: no python

Provides a drop-in replacement for Python's assert statement that remains active even when Python is run with -O (optimized mode). Currently at version 0.5.0, supports Python 3.9-3.12, and is released irregularly.

pip install safe-assert
error AttributeError: module 'safe_assert' has no attribute 'safe_assert'
cause Importing the module directly, then trying to call safe_assert.safe_assert() but the function is not exported at module level as an attribute.
fix
Use 'from safe_assert import safe_assert' instead of 'import safe_assert'.
error TypeError: 'module' object is not callable
cause Using 'import safe_assert' and then 'safe_assert(condition, message)' attempts to call the module itself, which is not callable.
fix
Use 'from safe_assert import safe_assert' and then call 'safe_assert(condition, message)'.
gotcha safe_assert is a function, not a replacement for the assert statement syntax. You cannot write `safe_assert x == 1`; you must call it as `safe_assert(x == 1)`.
fix Use function call syntax: safe_assert(condition, message)
deprecated Version 0.5.0 changes the return annotation from NoReturn to None. This is a typing-only change; runtime behavior is unaffected.
fix If you rely on the return type being NoReturn, update your type hints to None.
breaking Python 3.7 and 3.8 support dropped in version 0.5.0.
fix Upgrade to Python 3.9+ or pin safe-assert to <0.5.0.

Run this script normally or with python -O; safe_assert will still raise an error.

from safe_assert import safe_assert

x = 0
safe_assert(x != 0, "x should not be zero")  # raises safe_assert.AssertionError if False, even with python -O