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:

DeprecationWarning

Using deprecated features only supplied for backward compatibility

RuntimeWarning

Using features whose semantics are error-prone

SyntaxWarning

Using features whose syntax is error-prone

UserWarning

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):

message

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

category

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

module

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

lineno

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:

'always'

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

'default'

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)

'error'

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

'ignore'

w is ignored

'module'

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

'once'

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.

filterwarnings

filterwarnings(action,message='.*',category=Warning,
               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.

formatwarning

formatwarning(message,category,filename,lineno)

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

resetwarnings

resetwarnings(  )

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

showwarning

showwarning(message,category,filename,lineno,file=sys.stderr)

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.

warn

warn(message,category=UserWarning,stacklevel=1)

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):
    try: 
        return unicode(astr)
    except UnicodeError:
        warnings.warn("Invalid characters in (%s)"%astr, 
                      stacklevel=2)
        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