29.5.warnings — Warning control

Source code:Lib/warnings.py


Warning messages are typically issued in situations where it is useful to alertthe user of some condition in a program, where that condition (normally) doesn’twarrant raising an exception and terminating the program. For example, onemight want to issue a warning when a program uses an obsolete module.

Python programmers issue warnings by calling thewarn() function definedin this module. (C programmers usePyErr_WarnEx(); seeException Handling for details).

Warning messages are normally written tosys.stderr, but their dispositioncan be changed flexibly, from ignoring all warnings to turning them intoexceptions. The disposition of warnings can vary based on the warning category(see below), the text of the warning message, and the source location where itis issued. Repetitions of a particular warning for the same source location aretypically suppressed.

There are two stages in warning control: first, each time a warning is issued, adetermination is made whether a message should be issued or not; next, if amessage is to be issued, it is formatted and printed using a user-settable hook.

The determination whether to issue a warning message is controlled by thewarning filter, which is a sequence of matching rules and actions. Rules can beadded to the filter by callingfilterwarnings() and reset to its defaultstate by callingresetwarnings().

The printing of warning messages is done by callingshowwarning(), whichmay be overridden; the default implementation of this function formats themessage by callingformatwarning(), which is also available for use bycustom implementations.

See also

logging.captureWarnings() allows you to handle all warnings withthe standard logging infrastructure.

29.5.1. Warning Categories

There are a number of built-in exceptions that represent warning categories.This categorization is useful to be able to filter out groups of warnings. Thefollowing warnings category classes are currently defined:

ClassDescription
WarningThis is the base class of all warningcategory classes. It is a subclass ofException.
UserWarningThe default category forwarn().
DeprecationWarningBase category for warnings about deprecatedfeatures (ignored by default).
SyntaxWarningBase category for warnings about dubioussyntactic features.
RuntimeWarningBase category for warnings about dubiousruntime features.
FutureWarningBase category for warnings about constructsthat will change semantically in the future.
PendingDeprecationWarningBase category for warnings about featuresthat will be deprecated in the future(ignored by default).
ImportWarningBase category for warnings triggered duringthe process of importing a module (ignored bydefault).
UnicodeWarningBase category for warnings related toUnicode.
BytesWarningBase category for warnings related tobytes andbytearray.
ResourceWarningBase category for warnings related toresource usage.

While these are technically built-in exceptions, they are documented here,because conceptually they belong to the warnings mechanism.

User code can define additional warning categories by subclassing one of thestandard warning categories. A warning category must always be a subclass oftheWarning class.

29.5.2. The Warnings Filter

The warnings filter controls whether warnings are ignored, displayed, or turnedinto errors (raising an exception).

Conceptually, the warnings filter maintains an ordered list of filterspecifications; any specific warning is matched against each filterspecification in the list in turn until a match is found; the match determinesthe disposition of the match. Each entry is a tuple of the form (action,message,category,module,lineno), where:

  • action is one of the following strings:

    ValueDisposition
    "error"turn matching warnings into exceptions
    "ignore"never print matching warnings
    "always"always print matching warnings
    "default"print the first occurrence of matchingwarnings for each location where the warningis issued
    "module"print the first occurrence of matchingwarnings for each module where the warningis issued
    "once"print only the first occurrence of matchingwarnings, regardless of location
  • message is a string containing a regular expression that the start ofthe warning message must match. The expression is compiled to always becase-insensitive.

  • category is a class (a subclass ofWarning) of which the warningcategory must be a subclass in order to match.

  • module is a string containing a regular expression that the module name mustmatch. The expression is compiled to be case-sensitive.

  • lineno is an integer that the line number where the warning occurred mustmatch, or0 to match all line numbers.

Since theWarning class is derived from the built-inExceptionclass, to turn a warning into an error we simply raisecategory(message).

The warnings filter is initialized by-W options passed to the Pythoninterpreter command line. The interpreter saves the arguments for all-W options without interpretation insys.warnoptions; thewarnings module parses these when it is first imported (invalid optionsare ignored, after printing a message tosys.stderr).

29.5.2.1. Default Warning Filters

By default, Python installs several warning filters, which can be overridden bythe command-line options passed to-W and calls tofilterwarnings().

Changed in version 3.2:DeprecationWarning is now ignored by default in addition toPendingDeprecationWarning.

29.5.3. Temporarily Suppressing Warnings

If you are using code that you know will raise a warning, such as a deprecatedfunction, but do not want to see the warning, then it is possible to suppressthe warning using thecatch_warnings context manager:

importwarningsdeffxn():warnings.warn("deprecated",DeprecationWarning)withwarnings.catch_warnings():warnings.simplefilter("ignore")fxn()

While within the context manager all warnings will simply be ignored. Thisallows you to use known-deprecated code without having to see the warning whilenot suppressing the warning for other code that might not be aware of its useof deprecated code. Note: this can only be guaranteed in a single-threadedapplication. If two or more threads use thecatch_warnings contextmanager at the same time, the behavior is undefined.

29.5.4. Testing Warnings

To test warnings raised by code, use thecatch_warnings contextmanager. With it you can temporarily mutate the warnings filter to facilitateyour testing. For instance, do the following to capture all raised warnings tocheck:

importwarningsdeffxn():warnings.warn("deprecated",DeprecationWarning)withwarnings.catch_warnings(record=True)asw:# Cause all warnings to always be triggered.warnings.simplefilter("always")# Trigger a warning.fxn()# Verify some thingsassertlen(w)==1assertissubclass(w[-1].category,DeprecationWarning)assert"deprecated"instr(w[-1].message)

One can also cause all warnings to be exceptions by usingerror instead ofalways. One thing to be aware of is that if a warning has already beenraised because of aonce/default rule, then no matter what filters areset the warning will not be seen again unless the warnings registry related tothe warning has been cleared.

Once the context manager exits, the warnings filter is restored to its statewhen the context was entered. This prevents tests from changing the warningsfilter in unexpected ways between tests and leading to indeterminate testresults. Theshowwarning() function in the module is also restored toits original value. Note: this can only be guaranteed in a single-threadedapplication. If two or more threads use thecatch_warnings contextmanager at the same time, the behavior is undefined.

When testing multiple operations that raise the same kind of warning, itis important to test them in a manner that confirms each operation is raisinga new warning (e.g. set warnings to be raised as exceptions and check theoperations raise exceptions, check that the length of the warning listcontinues to increase after each operation, or else delete the previousentries from the warnings list before each new operation).

29.5.5. Updating Code For New Versions of Python

Warnings that are only of interest to the developer are ignored by default. Assuch you should make sure to test your code with typically ignored warningsmade visible. You can do this from the command-line by passing-Wdto the interpreter (this is shorthand for-Wdefault). This enablesdefault handling for all warnings, including those that are ignored by default.To change what action is taken for encountered warnings you simply change whatargument is passed to-W, e.g.-Werror. See the-W flag for more details on what is possible.

To programmatically do the same as-Wd, use:

warnings.simplefilter('default')

Make sure to execute this code as soon as possible. This prevents theregistering of what warnings have been raised from unexpectedly influencing howfuture warnings are treated.

Having certain warnings ignored by default is done to prevent a user fromseeing warnings that are only of interest to the developer. As you do notnecessarily have control over what interpreter a user uses to run their code,it is possible that a new version of Python will be released between yourrelease cycles. The new interpreter release could trigger new warnings in yourcode that were not there in an older interpreter, e.g.DeprecationWarning for a module that you are using. While you as adeveloper want to be notified that your code is using a deprecated module, to auser this information is essentially noise and provides no benefit to them.

Theunittest module has been also updated to use the'default'filter while running tests.

29.5.6. Available Functions

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

Issue a warning, or maybe ignore it or raise an exception. Thecategoryargument, if given, must be a warning category class (see above); it defaults toUserWarning. Alternativelymessage can be aWarning instance,in which casecategory will be ignored andmessage.__class__ will be used.In this case the message text will bestr(message). This function raises anexception if the particular warning issued is changed into an error by thewarnings filter see above. Thestacklevel argument can be used by wrapperfunctions written in Python, like this:

defdeprecation(message):warnings.warn(message,DeprecationWarning,stacklevel=2)

This makes the warning refer todeprecation()’s caller, rather than to thesource ofdeprecation() itself (since the latter would defeat the purposeof the warning message).

warnings.warn_explicit(message,category,filename,lineno,module=None,registry=None,module_globals=None)

This is a low-level interface to the functionality ofwarn(), passing inexplicitly the message, category, filename and line number, and optionally themodule name and the registry (which should be the__warningregistry__dictionary of the module). The module name defaults to the filename with.py stripped; if no registry is passed, the warning is never suppressed.message must be a string andcategory a subclass ofWarning ormessage may be aWarning instance, in which casecategory will beignored.

module_globals, if supplied, should be the global namespace in use by the codefor which the warning is issued. (This argument is used to support displayingsource for modules found in zipfiles or other non-filesystem importsources).

warnings.showwarning(message,category,filename,lineno,file=None,line=None)

Write a warning to a file. The default implementation callsformatwarning(message,category,filename,lineno,line) and writes theresulting string tofile, which defaults tosys.stderr. You may replacethis function with any callable by assigning towarnings.showwarning.line is a line of source code to be included in the warningmessage; ifline is not supplied,showwarning() willtry to read the line specified byfilename andlineno.

warnings.formatwarning(message,category,filename,lineno,line=None)

Format a warning the standard way. This returns a string which may containembedded newlines and ends in a newline.line is a line of source code tobe included in the warning message; ifline is not supplied,formatwarning() will try to read the line specified byfilename andlineno.

warnings.filterwarnings(action,message='',category=Warning,module='',lineno=0,append=False)

Insert an entry into the list ofwarnings filter specifications. The entry is inserted at the front by default; ifappend is true, it is inserted at the end. This checks the types of thearguments, compiles themessage andmodule regular expressions, andinserts them as a tuple in the list of warnings filters. Entries closer tothe front of the list override entries later in the list, if both match aparticular warning. Omitted arguments default to a value that matcheseverything.

warnings.simplefilter(action,category=Warning,lineno=0,append=False)

Insert a simple entry into the list ofwarnings filter specifications. The meaning of the function parameters is as forfilterwarnings(), but regular expressions are not needed as the filterinserted always matches any message in any module as long as the category andline number match.

warnings.resetwarnings()

Reset the warnings filter. This discards the effect of all previous calls tofilterwarnings(), including that of the-W command line optionsand calls tosimplefilter().

29.5.7. Available Context Managers

classwarnings.catch_warnings(*,record=False,module=None)

A context manager that copies and, upon exit, restores the warnings filterand theshowwarning() function.If therecord argument isFalse (the default) the context managerreturnsNone on entry. Ifrecord isTrue, a list isreturned that is progressively populated with objects as seen by a customshowwarning() function (which also suppresses output tosys.stdout).Each object in the list has attributes with the same names as the arguments toshowwarning().

Themodule argument takes a module that will be used instead of themodule returned when you importwarnings whose filter will beprotected. This argument exists primarily for testing thewarningsmodule itself.

Note

Thecatch_warnings manager works by replacing andthen later restoring the module’sshowwarning() function and internal list of filterspecifications. This means the context manager is modifyingglobal state and therefore is not thread-safe.