warnings
Updated March 13, 2026 · Modules
warnings stdlib debugging exceptions
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 warning
warnings.warn("This feature is deprecated", DeprecationWarning)
# Filter warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Catch warnings as errors
with warnings.catch_warnings():
warnings.simplefilter("error")
# Any warning raised inside this block becomes an exception
Key Functions
| Function | Description |
|---|---|
warnings.warn(message, category=UserWarning, stacklevel=1, source=None) | Issue a warning message |
warnings.filterwarnings(action, category=Warning, module='', lineno=0, append=False) | Add a filter to the warnings filter list |
warnings.simplefilter(action, category=Warning, lineno=0, append=False) | Insert a simple filter into the filter list |
warnings.resetwarnings() | Reset all filters to their default state |
warnings.showwarning(message, category, filename, lineno, file=None, line=None) | Function used to emit a warning (customizable) |
warnings.formatwarning(message, category, filename, lineno, line=None) | Format a warning as a string |
warnings.catch_warnings(*, record=False, module=None) | 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 warning
warnings.warn("This function will be removed in version 3.0")
# Deprecation warning with stacklevel
def old_function():
warnings.warn("old_function is deprecated", DeprecationWarning, stacklevel=2)
# FutureWarning with custom category
class BetaFeatureWarning(Warning):
pass
warnings.warn("This API is still in beta", BetaFeatureWarning)
Filtering warnings
import warnings
# Ignore all DeprecationWarnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Treat FutureWarning as errors
warnings.filterwarnings("error", category=FutureWarning)
# Ignore warnings from a specific module
warnings.filterwarnings("ignore", module="old_library")
# Show warnings only once per message
warnings.simplefilter("once")
Using catch_warnings context manager
import warnings
# Temporarily suppress all warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Any warning raised here will be ignored
import old_module
# Temporarily convert warnings to errors
with 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 inspection
with 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 warnings
import sys
def 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_showwarning
warnings.warn("Custom formatting!")
# Output: [MY APP] UserWarning: Custom formatting! at <stdin>:1
Common Patterns
Suppressing warnings in a library
import warnings
def 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 warnings
import os
if os.getenv("PYTHONWARNINGS") == "development":
warnings.filterwarnings("always") # Show every warning
warnings.filterwarnings("error", category=DeprecationWarning)
Filter warnings by message pattern
import warnings
import re
# Ignore warnings containing "deprecated" in the message
warnings.filterwarnings("ignore", message=r".*deprecated.*")
# Use a custom filter function
def 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 warningsUserWarning– default category forwarn()DeprecationWarning– deprecated features (ignored by default)FutureWarning– future changes in behaviorSyntaxWarning– questionable syntaxRuntimeWarning– runtime behavior that may be problematicImportWarning– import‑related issuesUnicodeWarning– Unicode‑related issuesBytesWarning– bytes‑related issuesResourceWarning– resource usage issues
Common mistakes
- Forgetting that
DeprecationWarningis ignored by default (setPYTHONWARNINGS=defaultor usewarnings.simplefilter('default')). - Setting
stacklevelincorrectly, causing the warning to point to the wrong line. - Using
filterwarningswithappend=Truebut expecting the filter to be applied immediately (filters are evaluated in order).