How do I issue and filter warnings in Python?
· Category: Python Programming
Short answer
The warnings module lets you emit non-fatal alerts for deprecated features or suspicious conditions. Users can filter warnings by category, module, or message using warnings.filterwarnings().
Steps
- Import
warnings. - Issue a warning with
warnings.warn("message", Category). - Control display with filters or command-line flags like
-W.
import warnings
def old_function():
warnings.warn("old_function is deprecated; use new_function()", DeprecationWarning)
return 42
# Filter to raise on deprecation warnings in tests
warnings.filterwarnings("error", category=DeprecationWarning)
# Command line: python -W error::DeprecationWarning script.py
Tips
- Use built-in categories:
DeprecationWarning,UserWarning,FutureWarning,RuntimeWarning. pytestautomatically converts warnings to errors when configured withfilterwarningsinpytest.ini.- Warnings are useful for library maintainers to communicate API changes without breaking code.
Common issues
- By default, Python suppresses
DeprecationWarningoutside__main__, so users may not see them. - Warning registries deduplicate identical warnings; repeated identical warnings may be silently suppressed.
- Overusing warnings creates noise that trains users to ignore them.