Python Glossary Русский

all Python 3warningsfunction

warnings.warn()

issuing warnings

Issues a warning — a message about a problem that does not stop the program; the filters decide whether it is shown. The default category is UserWarning.

Syntax

warnings.warn(message, category=None, stacklevel=1, source=None, *, skip_file_prefixes=())

Unlike raise, warn does not stop execution: the function carries on and the message goes to stderr — and only if the filters let it through; by default an identical warning from the same line is shown once, even in a loop. Unlike logging, the audience is not whoever watches the running program but the programmer calling your code: "this function is deprecated", "this argument will become required". The 'error' filter (the -W error option) turns a warning into an exception. stacklevel=2 points at the caller's line, not at the warn call itself.

Examples

import warnings
def area(r, unit=None):
    if unit is None:
        warnings.warn('укажите unit явно', FutureWarning, stacklevel=2)
    return 3 * r * r
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter('always')
    print(area(2))  # → 12
print(caught[0].category.__name__, caught[0].lineno)  # → FutureWarning 8
import warnings
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter('default', DeprecationWarning)
    for _ in range(3):
        warnings.warn('старый вызов', DeprecationWarning)
print(len(caught))  # → 1

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy