Exception Handling
Assert Statements
Debugging assertions and their limitations
Interview: Debugging techniques — tests understanding of when to use assert vs raise, and -O flag behavior
The assert statement is a debugging tool that tests a condition and raises AssertionError if the condition is False. Assertions should be used for internal checks that should never fail in correct code — NOT for input validation or business logic errors.
When to Use Assert
- Verifying invariants: conditions that should always be true
- Checking function post-conditions (return values)
- Debugging: catching impossible states during development
- Test code: verifying expected behavior
When NOT to Use Assert
- Input validation (use
raise ValueErrorinstead) - Business logic errors (assertions can be disabled with -O flag!)
- Data processing (assertions are not error handling)
- Any check that MUST run in production
Critical Warning
Assertions are REMOVED when Python runs with the -O (optimize) flag. Never use assert for security checks, input validation, or any check that must run in production.
Use Cases
Verifying pre/post conditions in algorithms
Checking class invariants during development
Debugging impossible states (code that should never execute)
Test assertions in unit tests
Documenting assumptions in code (assert len(x) > 0)
Common Mistakes
Using assert for input validation (disabled with -O flag)
assert with tuple: assert (x, "msg") ALWAYS passes (tuple is truthy!)
Using assert for security checks (can be bypassed with -O)
Not understanding that AssertionError is the exception type (not ValueError)
Putting side effects in assert (they won't run with -O flag)