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

FunctionDescription
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

ParameterTypeDefaultDescription
messagestrThe warning message text
categoryWarning subclassUserWarningThe warning category (e.g., DeprecationWarning, FutureWarning)
stacklevelint1How many levels up the call stack to report as the warning location
sourceobjectNoneThe object that caused the warning (used for __cause__ of the exception if the warning is turned into an error)

filterwarnings() Parameters

ParameterTypeDefaultDescription
actionstrOne of "error", "ignore", "always", "default", "module", or "once"
categoryWarning subclassWarningThe warning category to match
modulestr""Regular expression string to match the module name
linenoint0Line number to match; 0 matches all lines
appendboolFalseIf True, append the filter to the end of the list (instead of inserting at the front)

simplefilter() Parameters

ParameterTypeDefaultDescription
actionstrSame as filterwarnings()
categoryWarning subclassWarningThe warning category to match
linenoint0Line number to match; 0 matches all lines
appendboolFalseAppend 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 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).

See Also