Python etc / warnings

Published: 2022-09-13.

The module warnings allows to print, you’ve guessed it, warnings. Most often, it is used to warn users of a library that the module, function, or argument they use is deprecated.

import warnings

def g():
  return 2

def f():
    "f is deprecated, use g instead",
  return g()


The output: DeprecationWarning:
function f is deprecated, use g instead

Note that DeprecationWarning, as well as other warning categories, is built-in and doesn’t need to be imported from anywhere.

When running tests, pytest will collect all warnings and report them at the end. If you want to get the full traceback to the warning or enter there with a debugger, the easiest way to do so is to turn all warnings into exceptions:


On the production, you can suppress warnings. Or, better, turn them into proper log records, so they will be collected wherever you collect logs:

import logging