warnings.catch_warnings Captures Alerts

Emit and capture warnings with warnings.catch_warnings, promote them to errors with a filter, and inspect the recorded category and message.

PythonResilience

Code

pythonsnippet
33 lines
import warnings


def load_config(legacy: bool) -> dict[str, str]:
    if legacy:
        warnings.warn(
            "legacy config key will be removed",
            DeprecationWarning,
            stacklevel=2,
        )
    return {"legacy": str(legacy).lower()}


def main() -> None:
    with warnings.catch_warnings(record=True) as captured:
        warnings.simplefilter("always")
        load_config(legacy=True)
        load_config(legacy=False)

    print("captured:", len(captured))
    print("category:", captured[0].category.__name__)
    print("message:", captured[0].message)

    with warnings.catch_warnings():
        warnings.simplefilter("error")
        try:
            load_config(legacy=True)
        except DeprecationWarning as error:
            print("promoted to error:", error)


if __name__ == "__main__":
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

captured: 1
category: DeprecationWarning
message: legacy config key will be removed
promoted to error: legacy config key will be removed

What the code does

Everything happens inside the functions load_config and main.

A fresh value is allocated for the result; the arguments stay untouched.

What to watch for

  • warnings must be installed first — the snippet imports it directly.

Using it

Signature: def load_config(legacy: bool) -> dict[str, str]

The demo output is labeled (captured:, category:, message:), so every printed line maps back to its originating operation.

Execute the file and main walks through load_config, in that order.

Key statements

return {"legacy": str(legacy).lower()}
with warnings.catch_warnings(record=True) as captured:
    warnings.simplefilter("always")
    load_config(legacy=True)
    load_config(legacy=False)
except DeprecationWarning as error:
    print("promoted to error:", error)

Interactive Tools for This Topic

FAQ

Does `load_config` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
What does warnings.catch_warnings Captures Alerts print when run?
The script runs standalone; its 4 labeled outputs include `captured:`, `category:`, `message:`.