The warnings module lets you control how Python handles warning messages. Warnings are typically issued by Python itself or third‑party libraries to signal deprecated features, potential problems, or other noteworthy conditions that are not severe enough to raise an exception. With this module you can filter warnings by category, message, or module; convert warnings to errors; and suppress warnings entirely in specific contexts.
Syntax
import warnings# Issue a warningwarnings.warn("This feature is deprecated", DeprecationWarning)# Filter warningswarnings.filterwarnings("ignore", category=DeprecationWarning)# Catch warnings as errorswith warnings.catch_warnings(): warnings.simplefilter("error") # Any warning raised inside this block becomes an exception
Context manager to temporarily modify the warnings filter
warn() Parameters
Parameter
Type
Default
Description
message
str
—
The warning message text
category
Warning subclass
UserWarning
The warning category (e.g., DeprecationWarning, FutureWarning)
stacklevel
int
1
How many levels up the call stack to report as the warning location
source
object
None
The object that caused the warning (used for __cause__ of the exception if the warning is turned into an error)
filterwarnings() Parameters
Parameter
Type
Default
Description
action
str
—
One of "error", "ignore", "always", "default", "module", or "once"
category
Warning subclass
Warning
The warning category to match
module
str
""
Regular expression string to match the module name
lineno
int
0
Line number to match; 0 matches all lines
append
bool
False
If True, append the filter to the end of the list (instead of inserting at the front)
simplefilter() Parameters
Parameter
Type
Default
Description
action
str
—
Same as filterwarnings()
category
Warning subclass
Warning
The warning category to match
lineno
int
0
Line number to match; 0 matches all lines
append
bool
False
Append to the filter list (instead of inserting at the front)
Examples
Basic warning issuance
import warnings# Simple user warningwarnings.warn("This function will be removed in version 3.0")# Deprecation warning with stackleveldef old_function(): warnings.warn("old_function is deprecated", DeprecationWarning, stacklevel=2)# FutureWarning with custom categoryclass BetaFeatureWarning(Warning): passwarnings.warn("This API is still in beta", BetaFeatureWarning)
Filtering warnings
import warnings# Ignore all DeprecationWarningswarnings.filterwarnings("ignore", category=DeprecationWarning)# Treat FutureWarning as errorswarnings.filterwarnings("error", category=FutureWarning)# Ignore warnings from a specific modulewarnings.filterwarnings("ignore", module="old_library")# Show warnings only once per messagewarnings.simplefilter("once")
Using catch_warnings context manager
import warnings# Temporarily suppress all warningswith warnings.catch_warnings(): warnings.simplefilter("ignore") # Any warning raised here will be ignored import old_module# Temporarily convert warnings to errorswith warnings.catch_warnings(): warnings.simplefilter("error") try: warnings.warn("This will raise an exception") except Warning as e: print(f"Caught warning as error: {e}")# Record warnings for inspectionwith warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") warnings.warn("Recorded warning") print(f"Recorded {len(w)} warnings") for warning in w: print(warning.category.__name__, warning.message)
Custom warning display
import warningsimport sysdef custom_showwarning(message, category, filename, lineno, file=None, line=None): if file is None: file = sys.stderr file.write(f"[MY APP] {category.__name__}: {message} at {filename}:{lineno}\n")warnings.showwarning = custom_showwarningwarnings.warn("Custom formatting!")# Output: [MY APP] UserWarning: Custom formatting! at <stdin>:1
Common Patterns
Suppressing warnings in a library
import warningsdef public_api(): """Public function that uses a deprecated internal helper.""" with warnings.catch_warnings(): warnings.simplefilter("ignore", category=DeprecationWarning) return _internal_helper()def _internal_helper(): warnings.warn("This internal helper will be removed", DeprecationWarning) return 42
Turning on verbose warnings during development
import warningsimport osif os.getenv("PYTHONWARNINGS") == "development": warnings.filterwarnings("always") # Show every warning warnings.filterwarnings("error", category=DeprecationWarning)
Filter warnings by message pattern
import warningsimport re# Ignore warnings containing "deprecated" in the messagewarnings.filterwarnings("ignore", message=r".*deprecated.*")# Use a custom filter functiondef filter_by_message(message, category, filename, lineno, **kwargs): return "temporary" in str(message)warnings.filterwarnings("ignore", category=Warning, module=re.compile(".*"), lineno=0, append=False, message=filter_by_message)
Errors
Warning categories
The built‑in warning hierarchy (from exceptions.Warning):
Warning – base class for all warnings
UserWarning – default category for warn()
DeprecationWarning – deprecated features (ignored by default)
FutureWarning – future changes in behavior
SyntaxWarning – questionable syntax
RuntimeWarning – runtime behavior that may be problematic
ImportWarning – import‑related issues
UnicodeWarning – Unicode‑related issues
BytesWarning – bytes‑related issues
ResourceWarning – resource usage issues
Common mistakes
Forgetting that DeprecationWarning is ignored by default (set PYTHONWARNINGS=default or use warnings.simplefilter('default')).
Setting stacklevel incorrectly, causing the warning to point to the wrong line.
Using filterwarnings with append=True but expecting the filter to be applied immediately (filters are evaluated in order).