17.3 The warnings Module

Warnings are messages about errors or anomalies that may not be serious enough to be worth disrupting the program's control flow (as would happen by raising a normal exception). The warnings module offers you fine-grained control over which warnings are output and what happens to them. Your code can conditionally output a warning by calling function warn in module warnings. Other functions in the module let you control how warnings are formatted, set their destinations, and conditionally suppress some warnings (or transform some warnings into exceptions).

17.3.1 Classes

Module warnings supplies several exception classes representing warnings. Class Warning subclasses Exception and is the base class for all warnings. You may define your own warning classes; they must subclass Warning, either directly or via one of its other existing subclasses, which are:


Using deprecated features only supplied for backward compatibility


Using features whose semantics are error-prone


Using features whose syntax is error-prone


Other user-defined warnings that don't fit any of the above cases

17.3.2 Objects

In the current version of Python, there are no concrete warning objects. A warning is composed of a message (a text string), a category (a subclass of Warning), and two pieces of information that identify where the warning was raised from: module (name of the module raising the warning) and lineno (line number of the source code line raising the warning). Conceptually, you may think of these as attributes of a warning object w, and I use attribute notation later for clarity, but no specific warning object w actually exists.

17.3.3 Filters

At any time, module warnings keeps a list of active filters for warnings. When you import warnings for the first time in a run, the module examines sys.warnoptions to determine the initial set of filters. You can run Python with option -W to set sys.warnoptions for a given run. Do not rely on the initial set of filters being held specifically in sys.warnoptions, as this is an implementation aspect that may change in future releases of Python.

As each warning w occurs, warnings tests w against each filter until a filter matches. The matching filter determines what happens to w. Each filter is a tuple of five items. The first item, action, is a string that defines what happens on a match. The other four items, message, category, module, and lineno, control what it means for w to match the filter, and all conditions must be satisfied for a match. Here are the meanings of these items (using attribute notation to indicate conceptual attributes of w):


A regular expression object; the match condition is message.match(w.message) (the match is case-insensitive)


Warning or a subclass of Warning; the match condition is issubclass(w.category,category)


A regular expression object; the match condition is module.match(w.module) (the match is case-sensitive)


An integer; the match condition is lineno in (0, w.lineno), i.e., either lineno is 0, meaning w.lineno does not matter, or w.lineno must exactly equal lineno

Upon a match, the first field of the filter, the action, determines what happens:


w.message is output whether or not w has already occurred


w.message is output if, and only if, this is the first time w occurs from this specific location (i.e., this specific w.module, w.location pair)


w.category(w.message) is raised as an exception


w is ignored


w.message is output if, and only if, this is the first time w occurs from w.module


w.message is output if, and only if, this is the first time w occurs from any location

17.3.4 Functions

Module warnings supplies the following functions.


               module='.*',lineno=0, append=False)

Adds a filter to the list of active filters. When append is true, filterwarnings adds the filter after all other existing filters (i.e., appends the filter to the list of existing filters); otherwise filterwarnings inserts the filter before any other existing filter. All components, save action, have default values meaning match everything. As detailed above, message and module are pattern strings for regular expressions, category is some subclass of Warning, lineno is an integer, and action is a string that determines what happens when a message matches this filter.



Returns a string that represents the given warning with standard formatting.


resetwarnings(  )

Removes all filters from the list of filters. resetwarnings also discards any filters originally added with the -W command-line option.



Outputs the given warning to the given file object. Filter actions that output warnings call showwarning, letting argument file default to sys.stderr. To change what happens when filter actions output warnings, code your own function with this signature and bind it to warnings.showwarning.



Sends a warning, so that the filters examine and possibly output it. The location of the warning is the current function (caller of warn) if stacklevel is 1, or its caller if stacklevel is 2. Thus, passing 2 as the value of stacklevel lets you write functions that send warnings on their caller's behalf, such as:

def toUnicode(astr):
        return unicode(astr)
    except UnicodeError:
        warnings.warn("Invalid characters in (%s)"%astr, 
        return unicode(astr, errors='ignore')

Thanks to parameter stacklevel=2, the warning appears as coming from the caller of toUnicode, rather than from function toUnicode itself. This is particularly important when the action of the filter matching this warning is default or module, since these actions output a warning only the first time the warning occurs from a given location or module.

    Part III: Python Library and Extension Modules