IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
26.4.2 The Warnings Filter


26.4.2 The Warnings Filter

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

Conceptually, the warnings filter maintains an ordered list of filter specifications; any specific warning is matched against each filter specification in the list in turn until a match is found; the match determines the 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:

    Value Disposition
    "error" turn matching warnings into exceptions
    "ignore" never print matching warnings
    "always" always print matching warnings
    "default" print the first occurrence of matching warnings for each location where the warning is issued
    "module" print the first occurrence of matching warnings for each module where the warning is issued
    "once" print only the first occurrence of matching warnings, regardless of location

  • message is a string containing a regular expression that the warning message must match (the match is compiled to always be case-insensitive)

  • category is a class (a subclass of Warning) of which the warning category must be a subclass in order to match

  • module is a string containing a regular expression that the module name must match (the match is compiled to be case-sensitive)

  • lineno is an integer that the line number where the warning occurred must match, or 0 to match all line numbers

Since the Warning class is derived from the built-in Exception class, to turn a warning into an error we simply raise category(message).

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

The warnings that are ignored by default may be enabled by passing -Wd to the interpreter. This enables default handling for all warnings, including those that are normally ignored by default. This is particular useful for enabling ImportWarning when debugging problems importing a developed package. ImportWarning can also be enabled explicitly in Python code using:

    warnings.simplefilter('default', ImportWarning)

See About this document... for information on suggesting changes.