| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 |  | 
 | 2 | :mod:`warnings` --- Warning control | 
 | 3 | =================================== | 
 | 4 |  | 
 | 5 | .. index:: single: warnings | 
 | 6 |  | 
 | 7 | .. module:: warnings | 
 | 8 |    :synopsis: Issue warning messages and control their disposition. | 
 | 9 |  | 
 | 10 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 11 | Warning messages are typically issued in situations where it is useful to alert | 
 | 12 | the user of some condition in a program, where that condition (normally) doesn't | 
 | 13 | warrant raising an exception and terminating the program.  For example, one | 
 | 14 | might want to issue a warning when a program uses an obsolete module. | 
 | 15 |  | 
 | 16 | Python programmers issue warnings by calling the :func:`warn` function defined | 
 | 17 | in this module.  (C programmers use :cfunc:`PyErr_WarnEx`; see | 
 | 18 | :ref:`exceptionhandling` for details). | 
 | 19 |  | 
 | 20 | Warning messages are normally written to ``sys.stderr``, but their disposition | 
 | 21 | can be changed flexibly, from ignoring all warnings to turning them into | 
 | 22 | exceptions.  The disposition of warnings can vary based on the warning category | 
 | 23 | (see below), the text of the warning message, and the source location where it | 
 | 24 | is issued.  Repetitions of a particular warning for the same source location are | 
 | 25 | typically suppressed. | 
 | 26 |  | 
 | 27 | There are two stages in warning control: first, each time a warning is issued, a | 
 | 28 | determination is made whether a message should be issued or not; next, if a | 
 | 29 | message is to be issued, it is formatted and printed using a user-settable hook. | 
 | 30 |  | 
 | 31 | The determination whether to issue a warning message is controlled by the | 
 | 32 | warning filter, which is a sequence of matching rules and actions. Rules can be | 
 | 33 | added to the filter by calling :func:`filterwarnings` and reset to its default | 
 | 34 | state by calling :func:`resetwarnings`. | 
 | 35 |  | 
 | 36 | The printing of warning messages is done by calling :func:`showwarning`, which | 
 | 37 | may be overridden; the default implementation of this function formats the | 
 | 38 | message by calling :func:`formatwarning`, which is also available for use by | 
 | 39 | custom implementations. | 
 | 40 |  | 
 | 41 |  | 
 | 42 | .. _warning-categories: | 
 | 43 |  | 
 | 44 | Warning Categories | 
 | 45 | ------------------ | 
 | 46 |  | 
 | 47 | There are a number of built-in exceptions that represent warning categories. | 
 | 48 | This categorization is useful to be able to filter out groups of warnings.  The | 
 | 49 | following warnings category classes are currently defined: | 
 | 50 |  | 
 | 51 | +----------------------------------+-----------------------------------------------+ | 
 | 52 | | Class                            | Description                                   | | 
 | 53 | +==================================+===============================================+ | 
 | 54 | | :exc:`Warning`                   | This is the base class of all warning         | | 
 | 55 | |                                  | category classes.  It is a subclass of        | | 
 | 56 | |                                  | :exc:`Exception`.                             | | 
 | 57 | +----------------------------------+-----------------------------------------------+ | 
 | 58 | | :exc:`UserWarning`               | The default category for :func:`warn`.        | | 
 | 59 | +----------------------------------+-----------------------------------------------+ | 
 | 60 | | :exc:`DeprecationWarning`        | Base category for warnings about deprecated   | | 
 | 61 | |                                  | features.                                     | | 
 | 62 | +----------------------------------+-----------------------------------------------+ | 
 | 63 | | :exc:`SyntaxWarning`             | Base category for warnings about dubious      | | 
 | 64 | |                                  | syntactic features.                           | | 
 | 65 | +----------------------------------+-----------------------------------------------+ | 
 | 66 | | :exc:`RuntimeWarning`            | Base category for warnings about dubious      | | 
 | 67 | |                                  | runtime features.                             | | 
 | 68 | +----------------------------------+-----------------------------------------------+ | 
 | 69 | | :exc:`FutureWarning`             | Base category for warnings about constructs   | | 
 | 70 | |                                  | that will change semantically in the future.  | | 
 | 71 | +----------------------------------+-----------------------------------------------+ | 
 | 72 | | :exc:`PendingDeprecationWarning` | Base category for warnings about features     | | 
 | 73 | |                                  | that will be deprecated in the future         | | 
 | 74 | |                                  | (ignored by default).                         | | 
 | 75 | +----------------------------------+-----------------------------------------------+ | 
 | 76 | | :exc:`ImportWarning`             | Base category for warnings triggered during   | | 
 | 77 | |                                  | the process of importing a module (ignored by | | 
 | 78 | |                                  | default).                                     | | 
 | 79 | +----------------------------------+-----------------------------------------------+ | 
 | 80 | | :exc:`UnicodeWarning`            | Base category for warnings related to         | | 
 | 81 | |                                  | Unicode.                                      | | 
 | 82 | +----------------------------------+-----------------------------------------------+ | 
 | 83 |  | 
 | 84 | While these are technically built-in exceptions, they are documented here, | 
 | 85 | because conceptually they belong to the warnings mechanism. | 
 | 86 |  | 
 | 87 | User code can define additional warning categories by subclassing one of the | 
 | 88 | standard warning categories.  A warning category must always be a subclass of | 
 | 89 | the :exc:`Warning` class. | 
 | 90 |  | 
 | 91 |  | 
 | 92 | .. _warning-filter: | 
 | 93 |  | 
 | 94 | The Warnings Filter | 
 | 95 | ------------------- | 
 | 96 |  | 
 | 97 | The warnings filter controls whether warnings are ignored, displayed, or turned | 
 | 98 | into errors (raising an exception). | 
 | 99 |  | 
 | 100 | Conceptually, the warnings filter maintains an ordered list of filter | 
 | 101 | specifications; any specific warning is matched against each filter | 
 | 102 | specification in the list in turn until a match is found; the match determines | 
 | 103 | the disposition of the match.  Each entry is a tuple of the form (*action*, | 
 | 104 | *message*, *category*, *module*, *lineno*), where: | 
 | 105 |  | 
 | 106 | * *action* is one of the following strings: | 
 | 107 |  | 
 | 108 |   +---------------+----------------------------------------------+ | 
 | 109 |   | Value         | Disposition                                  | | 
 | 110 |   +===============+==============================================+ | 
 | 111 |   | ``"error"``   | turn matching warnings into exceptions       | | 
 | 112 |   +---------------+----------------------------------------------+ | 
 | 113 |   | ``"ignore"``  | never print matching warnings                | | 
 | 114 |   +---------------+----------------------------------------------+ | 
 | 115 |   | ``"always"``  | always print matching warnings               | | 
 | 116 |   +---------------+----------------------------------------------+ | 
 | 117 |   | ``"default"`` | print the first occurrence of matching       | | 
 | 118 |   |               | warnings for each location where the warning | | 
 | 119 |   |               | is issued                                    | | 
 | 120 |   +---------------+----------------------------------------------+ | 
 | 121 |   | ``"module"``  | print the first occurrence of matching       | | 
 | 122 |   |               | warnings for each module where the warning   | | 
 | 123 |   |               | is issued                                    | | 
 | 124 |   +---------------+----------------------------------------------+ | 
 | 125 |   | ``"once"``    | print only the first occurrence of matching  | | 
 | 126 |   |               | warnings, regardless of location             | | 
 | 127 |   +---------------+----------------------------------------------+ | 
 | 128 |  | 
 | 129 | * *message* is a string containing a regular expression that the warning message | 
 | 130 |   must match (the match is compiled to always be  case-insensitive) | 
 | 131 |  | 
 | 132 | * *category* is a class (a subclass of :exc:`Warning`) of which the warning | 
 | 133 |   category must be a subclass in order to match | 
 | 134 |  | 
 | 135 | * *module* is a string containing a regular expression that the module name must | 
 | 136 |   match (the match is compiled to be case-sensitive) | 
 | 137 |  | 
 | 138 | * *lineno* is an integer that the line number where the warning occurred must | 
 | 139 |   match, or ``0`` to match all line numbers | 
 | 140 |  | 
 | 141 | Since the :exc:`Warning` class is derived from the built-in :exc:`Exception` | 
 | 142 | class, to turn a warning into an error we simply raise ``category(message)``. | 
 | 143 |  | 
 | 144 | The warnings filter is initialized by :option:`-W` options passed to the Python | 
 | 145 | interpreter command line.  The interpreter saves the arguments for all | 
 | 146 | :option:`-W` options without interpretation in ``sys.warnoptions``; the | 
 | 147 | :mod:`warnings` module parses these when it is first imported (invalid options | 
 | 148 | are ignored, after printing a message to ``sys.stderr``). | 
 | 149 |  | 
 | 150 | The warnings that are ignored by default may be enabled by passing :option:`-Wd` | 
 | 151 | to the interpreter. This enables default handling for all warnings, including | 
 | 152 | those that are normally ignored by default. This is particular useful for | 
 | 153 | enabling ImportWarning when debugging problems importing a developed package. | 
 | 154 | ImportWarning can also be enabled explicitly in Python code using:: | 
 | 155 |  | 
 | 156 |    warnings.simplefilter('default', ImportWarning) | 
 | 157 |  | 
 | 158 |  | 
 | 159 | .. _warning-functions: | 
 | 160 |  | 
 | 161 | Available Functions | 
 | 162 | ------------------- | 
 | 163 |  | 
 | 164 |  | 
 | 165 | .. function:: warn(message[, category[, stacklevel]]) | 
 | 166 |  | 
 | 167 |    Issue a warning, or maybe ignore it or raise an exception.  The *category* | 
 | 168 |    argument, if given, must be a warning category class (see above); it defaults to | 
 | 169 |    :exc:`UserWarning`.  Alternatively *message* can be a :exc:`Warning` instance, | 
 | 170 |    in which case *category* will be ignored and ``message.__class__`` will be used. | 
 | 171 |    In this case the message text will be ``str(message)``. This function raises an | 
 | 172 |    exception if the particular warning issued is changed into an error by the | 
 | 173 |    warnings filter see above.  The *stacklevel* argument can be used by wrapper | 
 | 174 |    functions written in Python, like this:: | 
 | 175 |  | 
 | 176 |       def deprecation(message): | 
 | 177 |           warnings.warn(message, DeprecationWarning, stacklevel=2) | 
 | 178 |  | 
 | 179 |    This makes the warning refer to :func:`deprecation`'s caller, rather than to the | 
 | 180 |    source of :func:`deprecation` itself (since the latter would defeat the purpose | 
 | 181 |    of the warning message). | 
 | 182 |  | 
 | 183 |  | 
 | 184 | .. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]]) | 
 | 185 |  | 
 | 186 |    This is a low-level interface to the functionality of :func:`warn`, passing in | 
 | 187 |    explicitly the message, category, filename and line number, and optionally the | 
 | 188 |    module name and the registry (which should be the ``__warningregistry__`` | 
 | 189 |    dictionary of the module).  The module name defaults to the filename with | 
 | 190 |    ``.py`` stripped; if no registry is passed, the warning is never suppressed. | 
 | 191 |    *message* must be a string and *category* a subclass of :exc:`Warning` or | 
 | 192 |    *message* may be a :exc:`Warning` instance, in which case *category* will be | 
 | 193 |    ignored. | 
 | 194 |  | 
 | 195 |    *module_globals*, if supplied, should be the global namespace in use by the code | 
 | 196 |    for which the warning is issued.  (This argument is used to support displaying | 
 | 197 |    source for modules found in zipfiles or other non-filesystem import sources, and | 
 | 198 |    was added in Python 2.5.) | 
 | 199 |  | 
 | 200 |  | 
 | 201 | .. function:: showwarning(message, category, filename, lineno[, file]) | 
 | 202 |  | 
 | 203 |    Write a warning to a file.  The default implementation calls | 
 | 204 |    ``formatwarning(message, category, filename, lineno)`` and writes the resulting | 
 | 205 |    string to *file*, which defaults to ``sys.stderr``.  You may replace this | 
 | 206 |    function with an alternative implementation by assigning to | 
 | 207 |    ``warnings.showwarning``. | 
 | 208 |  | 
 | 209 |  | 
 | 210 | .. function:: formatwarning(message, category, filename, lineno) | 
 | 211 |  | 
 | 212 |    Format a warning the standard way.  This returns a string  which may contain | 
 | 213 |    embedded newlines and ends in a newline. | 
 | 214 |  | 
 | 215 |  | 
 | 216 | .. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]]) | 
 | 217 |  | 
 | 218 |    Insert an entry into the list of warnings filters.  The entry is inserted at the | 
 | 219 |    front by default; if *append* is true, it is inserted at the end. This checks | 
 | 220 |    the types of the arguments, compiles the message and module regular expressions, | 
 | 221 |    and inserts them as a tuple in the  list of warnings filters.  Entries closer to | 
 | 222 |    the front of the list override entries later in the list, if both match a | 
 | 223 |    particular warning.  Omitted arguments default to a value that matches | 
 | 224 |    everything. | 
 | 225 |  | 
 | 226 |  | 
 | 227 | .. function:: simplefilter(action[, category[, lineno[, append]]]) | 
 | 228 |  | 
 | 229 |    Insert a simple entry into the list of warnings filters. The meaning of the | 
 | 230 |    function parameters is as for :func:`filterwarnings`, but regular expressions | 
 | 231 |    are not needed as the filter inserted always matches any message in any module | 
 | 232 |    as long as the category and line number match. | 
 | 233 |  | 
 | 234 |  | 
 | 235 | .. function:: resetwarnings() | 
 | 236 |  | 
 | 237 |    Reset the warnings filter.  This discards the effect of all previous calls to | 
 | 238 |    :func:`filterwarnings`, including that of the :option:`-W` command line options | 
 | 239 |    and calls to :func:`simplefilter`. | 
 | 240 |  |