Errors

Warnings

warnings report soft problems without immediately stopping the program.

Capture warnings in tests when the returned value still matters but the migration notice must be asserted.

Source

import warnings


def old_name():
    warnings.warn("old_name is deprecated", DeprecationWarning, stacklevel=2)
    return "result"

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always", DeprecationWarning)
    print(old_name())
    print(caught[0].category.__name__)
    print(str(caught[0].message))

Output

result
DeprecationWarning
old_name is deprecated
code pathDeprecationWarningexecution continues
A warning is a soft signal: the message is reported, but execution continues unless filters elevate it.

A filter can promote selected warnings to exceptions, which is useful in CI when deprecated calls should fail the build.

Source

with warnings.catch_warnings():
    warnings.simplefilter("error", DeprecationWarning)
    try:
        old_name()
    except DeprecationWarning:
        print("warning became error")

Output

warning became error

Notes

See also

Run the complete example

Example code

Expected output

result
DeprecationWarning
old_name is deprecated
warning became error

Execution time appears here after you run the example.