On this page
  1. warnings
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Pointing Warnings at the Caller (stacklevel=2)
  7. 2. Turning Warnings into Errors in CI / Tests
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

warnings

Prev: venv | Up: stdlib_module | Next: wave
Rel: sys, sysconfig, builtins, dataclasses, contextlib
Ref: docs.python.org — warnings
Tags: #public #python3 #stdlib


Import

import warnings

Overview

Emits, filters, and tests non-fatal runtime warnings (warn, filterwarnings, catch_warnings)—the standard mechanism for signaling deprecated APIs (DeprecationWarning, FutureWarning) or questionable usage without crashing the caller.

Quick Start

import warnings

def old_helper() -> int:
    warnings.warn("old_helper() is deprecated; use new_helper()", DeprecationWarning, stacklevel=2)
    return 42

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    assert old_helper() == 42
    assert len(caught) == 1 and caught[0].category is DeprecationWarning

Implementation Walkthrough

1. Pointing Warnings at the Caller (stacklevel=2)

Always pass stacklevel=2 (or higher for nested helpers) so the warning points to the caller's line rather than the warnings.warn() line inside your library:

import warnings

def deprecated_parse(text: str) -> str:
    warnings.warn(
        "deprecated_parse() will be removed in 2.0",
        DeprecationWarning,
        stacklevel=2,
    )
    return text.strip()

2. Turning Warnings into Errors in CI / Tests

Run tests with python -W error (or filterwarnings = ["error"] in pyproject.toml) to catch deprecations before they become breaking upgrades.

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes