Warnings

Python Warning Control

See also

Python warnings module documentation

The warnings module in Python provides a way to control how warnings handled within a Python script. It allows developers to emit warning messages to alert users of potential issues or unexpected behavior in their code. It is commonly used when a method is marked for deprecation, but can also be applied to warn about unexpected runtime conditions.

The warnings module provides several functions to create warnings, and other functions to control how they are handled or displayed, including:

  • warn(message, warning_type=None, stacklevel=1):

Generates a warning message. The message parameter is the warning message string, warning_type is the type of warning, and stacklevel is the number of stack frames to skip before recording the warning location.

  • warn_explicit(message, warning_type, filename, lineno, module=None, registry=None, module_globals=None):

Generates a warning message with explicit details about the warning location, such as the filename and line number. This is useful when you want to generate warnings for external code or for custom warnings.

  • filterwarnings(action, message="", category=Warning, module="", lineno=0, append=False):

Controls how warnings are filtered and displayed. The action parameter can be one of ignore, always, module, once, or default, which specifies how to filter the warning. The message, category, module, and lineno parameters are used to identify which specific warnings to filter.

The warnings module also provides a default warning handling mechanism, which displays warning messages on the console via stderr. However, script authors can customize the warning handling behavior by setting the warnings.showwarning function to a custom function that handles warnings as may be desired.

This mechanism is applied throughout the CSD Python API, giving script authors control over how these warnings are handled.

To throw exceptions whenever a deprecated function is called, for example, the following may be used:

>>> import warnings
>>> warnings.filterwarnings('error', '.*deprecated.*', DeprecationWarning, '.*', 0)

To instead ignore all cases of deprecated functions, use:

>>> warnings.filterwarnings('ignore', '.*deprecated.*', DeprecationWarning, '.*', 0)