The warnings Module

Published by Brayan K

The warnings module lets your code raise non-fatal alerts — like deprecation notices — that surface a message to the caller without stopping the program.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A warning reports a condition; the filter decides what happens next

A warning can tell callers that an API is deprecated or a recoverable condition deserves attention. It is not automatically a raised exception. The active filter can display it, ignore it, record it or turn it into an exception. Keep that caller-controlled policy separate from the library code that reports the condition.

import warnings

def old_name():
    warnings.warn("use new_name instead", DeprecationWarning, stacklevel=2)
    return "result"

with warnings.catch_warnings(record=True) as captured:
    warnings.simplefilter("always")
    result = old_name()
print(result)
print(len(captured))
print(captured[0].category.__name__)
print(str(captured[0].message))

# ✅ Expected output:
# result
# 1
# DeprecationWarning
# use new_name instead

record=True returns a list of warning records instead of printing the usual diagnostic. Each record contains the category, message and attribution metadata. The example prints stable message/category fields rather than machine-specific filenames. The operation continues because the chosen action is always, not error.

Do not assume that a default interpreter run shows every warning. DeprecationWarning is commonly ignored outside __main__, while test runners, command-line options and environment settings can alter the filters. These examples choose their policy explicitly so the lesson does not depend on your startup configuration.

Turning a warning into an error changes control flow

import warnings

with warnings.catch_warnings():
    warnings.simplefilter("error", UserWarning)
    warnings.warn("configuration needs attention", UserWarning)

# ✅ Expected error:
# UserWarning: configuration needs attention

The warning category is also an exception class, so error promotes this warning into that category’s exception. Code after the warning call is not reached unless something catches it. This can make deprecations fail a test suite without requiring every library to raise unconditionally.

import warnings

try:
    with warnings.catch_warnings():
        warnings.simplefilter("error", DeprecationWarning)
        warnings.warn("legacy option", DeprecationWarning)
except DeprecationWarning as error:
    print("caught:", error)
print("continued after handling")

# ✅ Expected output:
# caught: legacy option
# continued after handling

raise UserWarning(...) directly is different: it raises an exception regardless of the warning filters. Use warnings.warn when callers should control the disposition. Exception Handling owns ordinary exception propagation and handling.

The first matching filter wins

import warnings

with warnings.catch_warnings(record=True) as captured:
    warnings.simplefilter("always", UserWarning)
    warnings.filterwarnings("ignore", message=r"legacy option",
                            category=UserWarning)
    warnings.warn("legacy option is deprecated", UserWarning)
    warnings.warn("new condition", UserWarning)
print([str(record.message) for record in captured])

# ✅ Expected output:
# ['new condition']

New filter entries are normally inserted at the front. The narrow ignore rule is therefore considered before the broader always rule. append=True changes where a new rule is placed; it does not make a rule more specific or automatically higher priority. Reversing insertion order can change the result.

filterwarnings can select by category, message, module and line number. Its message argument is a case-insensitive regular expression matched at the beginning of the warning text; its module pattern is case-sensitive. Do not assume the API’s regex semantics are identical to every command-line warning option. Keep suppressions narrow enough that unrelated warnings remain visible.

Repeated warnings have a location-sensitive policy

import warnings

for action in ["default", "always"]:
    with warnings.catch_warnings(record=True) as captured:
        warnings.simplefilter(action, UserWarning)
        for _ in range(3):
            warnings.warn("same condition", UserWarning)
    print(action, len(captured))

# ✅ Expected output:
# default 1
# always 3

With default handling, repeated warnings with the same message, category, module and line are suppressed after the first occurrence. always reports each occurrence. The module action ignores line differences when deciding repetition, and once is broader still. These policies are about warning identity and location, not the number of times your underlying operation ran.

Warning registries can make a later test see fewer records than expected if it relies on prior default suppression. For a test that needs to observe every emission, use an explicit always filter inside a controlled capture context. Do not clear arbitrary module state merely to make a count look right.

stacklevel points callers toward the code they can change

import inspect
import warnings

def legacy():
    warnings.warn("call modern instead", DeprecationWarning, stacklevel=2)

with warnings.catch_warnings(record=True) as captured:
    warnings.simplefilter("always")
    frame = inspect.currentframe()
    try:
        expected_line = frame.f_lineno + 1
        legacy()
    finally:
        del frame
print(captured[0].lineno == expected_line)
print(captured[0].category.__name__)

# ✅ Expected output:
# True
# DeprecationWarning

stacklevel=1 attributes the warning to the warn call itself. A simple wrapper uses 2 to attribute it to the wrapper’s caller. More wrapper layers need a deliberate attribution decision; copying the same number into every helper can point at the wrong place. stacklevel changes the reported location, not the warning category.

The example compares line numbers rather than printing a path or a source-line value. The temporary frame reference is removed explicitly. Introspection with inspect owns frame and signature inspection.

A custom category lets callers select your library’s condition

import warnings

class LegacyOptionWarning(DeprecationWarning):
    pass

with warnings.catch_warnings(record=True) as captured:
    warnings.simplefilter("always")
    warnings.filterwarnings("ignore", category=LegacyOptionWarning)
    warnings.warn("old option", LegacyOptionWarning)
    warnings.warn("different concern", UserWarning)
print([record.category.__name__ for record in captured])

# ✅ Expected output:
# ['UserWarning']

A custom category must inherit from Warning, commonly through a meaningful built-in subclass. Callers can then filter that condition without suppressing every UserWarning or every warning in the process. Include a concrete replacement or corrective action in the message when one is available.

import warnings

warnings.warn("not a valid category", ValueError)

# ✅ Expected error:
# TypeError: category must be a Warning subclass, not 'type'

Keep temporary filter changes inside their intended lifetime

import warnings

with warnings.catch_warnings(record=True) as outer:
    warnings.simplefilter("always", UserWarning)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", UserWarning)
        warnings.warn("hidden inside", UserWarning)
    warnings.warn("visible outside", UserWarning)
print([str(record.message) for record in outer])

# ✅ Expected output:
# ['visible outside']

catch_warnings restores the surrounding warning policy on exit, including when the body raises. That makes it suitable for a narrow test or operation. A library should not normally install a permanent ignore-everything filter during import; it would change what unrelated application code can observe.

Concurrency needs extra care: Python 3.11–3.13 manage these contexts through shared warning state. Python 3.14 adds context-aware behavior controlled by a runtime flag, whose default differs between conventional and free-threaded builds. The sequential examples here do not claim that overlapping warning contexts are safe under every runtime configuration.

Complete a test that checks an emitted warning

Capture a deprecation explicitly, record every occurrence, and inspect its message. Fill the capture option and filter action. The code tests an emission without printing the default filename-bearing diagnostic.

import warnings

with warnings.catch_warnings(record=___) as captured:
    warnings.simplefilter(___, DeprecationWarning)
    warnings.warn("use the named option", DeprecationWarning)
print(len(captured))
print(str(captured[0].message))

# 👉 replace ___ with True
# 👉 replace ___ with "always"

# ✅ Expected output:
# 1
# use the named option

Support a legacy option without hiding conflicting arguments

Write a function that accepts either modern limit or legacy count. Using count emits a custom DeprecationWarning subclass and returns that value. Supplying both is an ordinary ValueError, and supplying neither uses 10. Capture and print the legacy result and warning message; then demonstrate that conflicting inputs are rejected. Keep warning policy outside the function.

import warnings

class LegacyCountWarning(DeprecationWarning):
    pass

def choose_limit(*, limit=None, count=None):
    if limit is not None and count is not None:
        raise ValueError("choose limit or count, not both")
    if count is not None:
        warnings.warn("count is deprecated; use limit",
                      LegacyCountWarning, stacklevel=2)
        return count
    return 10 if limit is None else limit

with warnings.catch_warnings(record=True) as captured:
    warnings.simplefilter("always", LegacyCountWarning)
    print(choose_limit(count=4))
print(str(captured[0].message))
print(choose_limit())
try:
    choose_limit(limit=3, count=4)
except ValueError as error:
    print(error)

# ✅ Expected output:
# 4
# count is deprecated; use limit
# 10
# choose limit or count, not both

Practice quiz

What does this program print? import warnings with warnings.catch_warnings(record=True) as records: warnings.simplefilter("always") warnings.warn("notice", UserWarning) print(len(records))

  • 1
  • 0
  • None
  • UserWarning

Answer: 1. Recording collects the warning while always ensures it is emitted.

What does the error filter action do?

  • Changes every warning to ValueError
  • Raises the warning category as an exception
  • Writes only to stdout
  • Retries the warning call

Answer: Raises the warning category as an exception. The warning’s own category becomes the raised exception type.

What does this program print? import warnings with warnings.catch_warnings(record=True) as records: warnings.simplefilter("ignore", UserWarning) warnings.warn("notice", UserWarning) print(len(records))

  • 1
  • None
  • 0
  • UserWarning

Answer: 0. An ignored warning does not become a captured record.

Which filter rule takes effect when several match?

  • The last matching rule
  • The most specific rule automatically
  • Every matching rule runs
  • The first matching rule in the filter list

Answer: The first matching rule in the filter list. Ordering matters; new rules normally go at the front.

What does this program print? import warnings with warnings.catch_warnings(record=True) as records: warnings.simplefilter("always") warnings.warn("use modern", DeprecationWarning) print(records[0].category.__name__)

  • DeprecationWarning
  • Warning
  • UserWarning
  • ValueError

Answer: DeprecationWarning. Capture retains the emitted category.

A simple warning wrapper uses stacklevel=2. What is its purpose?

  • To emit the warning twice
  • To attribute the warning to the wrapper’s caller
  • To raise a different category
  • To enable thread safety

Answer: To attribute the warning to the wrapper’s caller. Attribution should point to the code whose caller can make the migration.

What does this program print? import warnings with warnings.catch_warnings(record=True) as records: warnings.simplefilter("always") for _ in range(3): warnings.warn("repeat", UserWarning) print(len(records))

  • 1
  • 0
  • 3
  • 2

Answer: 3. always records each emission, including repeated locations.

What should a library do when it wants callers to control a deprecation policy?

  • Install a global ignore-all filter
  • Raise UserWarning directly in all cases
  • Assume defaults never change
  • Emit a meaningful category with warnings.warn

Answer: Emit a meaningful category with warnings.warn. Callers can then display, capture, suppress narrowly or escalate that category.

Continue this course

Related lessons