Python › Debugging & Profiling
How do assert statements work for debugging, and why should they NOT be relied upon for production input validation?
IntermediateAnswer
'assert condition, message' raises an AssertionError with the given message if the condition is falsy — useful for catching PROGRAMMER errors and internal invariant violations during development, but assertions are STRIPPED ENTIRELY when Python runs with the -O (optimize) flag, so they must never be used to validate untrusted external input in production code.
def calculate_discount(price, percent):
assert 0 <= percent <= 100, f"Invalid percent: {percent}" # catches a programmer bug during dev
return price * (1 - percent / 100)
# python -O script.py -- this assert would be silently REMOVED, no validation at all!Real-world example Catching an internal logic bug (like an invariant violation) during development and testing, but NOT for validating user input.