Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +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 | |
| 11 | .. versionadded:: 2.1 |
| 12 | |
| 13 | Warning messages are typically issued in situations where it is useful to alert |
| 14 | the user of some condition in a program, where that condition (normally) doesn't |
| 15 | warrant raising an exception and terminating the program. For example, one |
| 16 | might want to issue a warning when a program uses an obsolete module. |
| 17 | |
| 18 | Python programmers issue warnings by calling the :func:`warn` function defined |
Benjamin Peterson | 092a1f7 | 2008-03-31 21:57:13 +0000 | [diff] [blame] | 19 | in this module. (C programmers use :cfunc:`PyErr_WarnEx`; see |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 20 | :ref:`exceptionhandling` for details). |
| 21 | |
| 22 | Warning messages are normally written to ``sys.stderr``, but their disposition |
| 23 | can be changed flexibly, from ignoring all warnings to turning them into |
| 24 | exceptions. The disposition of warnings can vary based on the warning category |
| 25 | (see below), the text of the warning message, and the source location where it |
| 26 | is issued. Repetitions of a particular warning for the same source location are |
| 27 | typically suppressed. |
| 28 | |
| 29 | There are two stages in warning control: first, each time a warning is issued, a |
| 30 | determination is made whether a message should be issued or not; next, if a |
| 31 | message is to be issued, it is formatted and printed using a user-settable hook. |
| 32 | |
| 33 | The determination whether to issue a warning message is controlled by the |
| 34 | warning filter, which is a sequence of matching rules and actions. Rules can be |
| 35 | added to the filter by calling :func:`filterwarnings` and reset to its default |
| 36 | state by calling :func:`resetwarnings`. |
| 37 | |
| 38 | The printing of warning messages is done by calling :func:`showwarning`, which |
| 39 | may be overridden; the default implementation of this function formats the |
| 40 | message by calling :func:`formatwarning`, which is also available for use by |
| 41 | custom implementations. |
| 42 | |
| 43 | |
| 44 | .. _warning-categories: |
| 45 | |
| 46 | Warning Categories |
| 47 | ------------------ |
| 48 | |
| 49 | There are a number of built-in exceptions that represent warning categories. |
| 50 | This categorization is useful to be able to filter out groups of warnings. The |
| 51 | following warnings category classes are currently defined: |
| 52 | |
| 53 | +----------------------------------+-----------------------------------------------+ |
| 54 | | Class | Description | |
| 55 | +==================================+===============================================+ |
| 56 | | :exc:`Warning` | This is the base class of all warning | |
| 57 | | | category classes. It is a subclass of | |
| 58 | | | :exc:`Exception`. | |
| 59 | +----------------------------------+-----------------------------------------------+ |
| 60 | | :exc:`UserWarning` | The default category for :func:`warn`. | |
| 61 | +----------------------------------+-----------------------------------------------+ |
| 62 | | :exc:`DeprecationWarning` | Base category for warnings about deprecated | |
| 63 | | | features. | |
| 64 | +----------------------------------+-----------------------------------------------+ |
| 65 | | :exc:`SyntaxWarning` | Base category for warnings about dubious | |
| 66 | | | syntactic features. | |
| 67 | +----------------------------------+-----------------------------------------------+ |
| 68 | | :exc:`RuntimeWarning` | Base category for warnings about dubious | |
| 69 | | | runtime features. | |
| 70 | +----------------------------------+-----------------------------------------------+ |
| 71 | | :exc:`FutureWarning` | Base category for warnings about constructs | |
| 72 | | | that will change semantically in the future. | |
| 73 | +----------------------------------+-----------------------------------------------+ |
| 74 | | :exc:`PendingDeprecationWarning` | Base category for warnings about features | |
| 75 | | | that will be deprecated in the future | |
| 76 | | | (ignored by default). | |
| 77 | +----------------------------------+-----------------------------------------------+ |
| 78 | | :exc:`ImportWarning` | Base category for warnings triggered during | |
| 79 | | | the process of importing a module (ignored by | |
| 80 | | | default). | |
| 81 | +----------------------------------+-----------------------------------------------+ |
| 82 | | :exc:`UnicodeWarning` | Base category for warnings related to | |
| 83 | | | Unicode. | |
| 84 | +----------------------------------+-----------------------------------------------+ |
| 85 | |
| 86 | While these are technically built-in exceptions, they are documented here, |
| 87 | because conceptually they belong to the warnings mechanism. |
| 88 | |
| 89 | User code can define additional warning categories by subclassing one of the |
| 90 | standard warning categories. A warning category must always be a subclass of |
| 91 | the :exc:`Warning` class. |
| 92 | |
| 93 | |
| 94 | .. _warning-filter: |
| 95 | |
| 96 | The Warnings Filter |
| 97 | ------------------- |
| 98 | |
| 99 | The warnings filter controls whether warnings are ignored, displayed, or turned |
| 100 | into errors (raising an exception). |
| 101 | |
| 102 | Conceptually, the warnings filter maintains an ordered list of filter |
| 103 | specifications; any specific warning is matched against each filter |
| 104 | specification in the list in turn until a match is found; the match determines |
| 105 | the disposition of the match. Each entry is a tuple of the form (*action*, |
| 106 | *message*, *category*, *module*, *lineno*), where: |
| 107 | |
| 108 | * *action* is one of the following strings: |
| 109 | |
| 110 | +---------------+----------------------------------------------+ |
| 111 | | Value | Disposition | |
| 112 | +===============+==============================================+ |
| 113 | | ``"error"`` | turn matching warnings into exceptions | |
| 114 | +---------------+----------------------------------------------+ |
| 115 | | ``"ignore"`` | never print matching warnings | |
| 116 | +---------------+----------------------------------------------+ |
| 117 | | ``"always"`` | always print matching warnings | |
| 118 | +---------------+----------------------------------------------+ |
| 119 | | ``"default"`` | print the first occurrence of matching | |
| 120 | | | warnings for each location where the warning | |
| 121 | | | is issued | |
| 122 | +---------------+----------------------------------------------+ |
| 123 | | ``"module"`` | print the first occurrence of matching | |
| 124 | | | warnings for each module where the warning | |
| 125 | | | is issued | |
| 126 | +---------------+----------------------------------------------+ |
| 127 | | ``"once"`` | print only the first occurrence of matching | |
| 128 | | | warnings, regardless of location | |
| 129 | +---------------+----------------------------------------------+ |
| 130 | |
| 131 | * *message* is a string containing a regular expression that the warning message |
| 132 | must match (the match is compiled to always be case-insensitive) |
| 133 | |
| 134 | * *category* is a class (a subclass of :exc:`Warning`) of which the warning |
| 135 | category must be a subclass in order to match |
| 136 | |
| 137 | * *module* is a string containing a regular expression that the module name must |
| 138 | match (the match is compiled to be case-sensitive) |
| 139 | |
| 140 | * *lineno* is an integer that the line number where the warning occurred must |
| 141 | match, or ``0`` to match all line numbers |
| 142 | |
| 143 | Since the :exc:`Warning` class is derived from the built-in :exc:`Exception` |
| 144 | class, to turn a warning into an error we simply raise ``category(message)``. |
| 145 | |
| 146 | The warnings filter is initialized by :option:`-W` options passed to the Python |
| 147 | interpreter command line. The interpreter saves the arguments for all |
| 148 | :option:`-W` options without interpretation in ``sys.warnoptions``; the |
| 149 | :mod:`warnings` module parses these when it is first imported (invalid options |
| 150 | are ignored, after printing a message to ``sys.stderr``). |
| 151 | |
| 152 | The warnings that are ignored by default may be enabled by passing :option:`-Wd` |
| 153 | to the interpreter. This enables default handling for all warnings, including |
| 154 | those that are normally ignored by default. This is particular useful for |
| 155 | enabling ImportWarning when debugging problems importing a developed package. |
| 156 | ImportWarning can also be enabled explicitly in Python code using:: |
| 157 | |
| 158 | warnings.simplefilter('default', ImportWarning) |
| 159 | |
| 160 | |
| 161 | .. _warning-functions: |
| 162 | |
| 163 | Available Functions |
| 164 | ------------------- |
| 165 | |
| 166 | |
| 167 | .. function:: warn(message[, category[, stacklevel]]) |
| 168 | |
| 169 | Issue a warning, or maybe ignore it or raise an exception. The *category* |
| 170 | argument, if given, must be a warning category class (see above); it defaults to |
| 171 | :exc:`UserWarning`. Alternatively *message* can be a :exc:`Warning` instance, |
| 172 | in which case *category* will be ignored and ``message.__class__`` will be used. |
| 173 | In this case the message text will be ``str(message)``. This function raises an |
| 174 | exception if the particular warning issued is changed into an error by the |
| 175 | warnings filter see above. The *stacklevel* argument can be used by wrapper |
| 176 | functions written in Python, like this:: |
| 177 | |
| 178 | def deprecation(message): |
| 179 | warnings.warn(message, DeprecationWarning, stacklevel=2) |
| 180 | |
| 181 | This makes the warning refer to :func:`deprecation`'s caller, rather than to the |
| 182 | source of :func:`deprecation` itself (since the latter would defeat the purpose |
| 183 | of the warning message). |
| 184 | |
| 185 | |
| 186 | .. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]]) |
| 187 | |
| 188 | This is a low-level interface to the functionality of :func:`warn`, passing in |
| 189 | explicitly the message, category, filename and line number, and optionally the |
| 190 | module name and the registry (which should be the ``__warningregistry__`` |
| 191 | dictionary of the module). The module name defaults to the filename with |
| 192 | ``.py`` stripped; if no registry is passed, the warning is never suppressed. |
| 193 | *message* must be a string and *category* a subclass of :exc:`Warning` or |
| 194 | *message* may be a :exc:`Warning` instance, in which case *category* will be |
| 195 | ignored. |
| 196 | |
| 197 | *module_globals*, if supplied, should be the global namespace in use by the code |
| 198 | for which the warning is issued. (This argument is used to support displaying |
Brett Cannon | 338d418 | 2007-12-09 05:09:37 +0000 | [diff] [blame] | 199 | source for modules found in zipfiles or other non-filesystem import |
| 200 | sources). |
| 201 | |
| 202 | .. versionchanged:: 2.5 |
Georg Brandl | 4aa8df2 | 2008-04-13 07:07:44 +0000 | [diff] [blame] | 203 | Added the *module_globals* parameter. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 204 | |
| 205 | |
Christian Heimes | 28104c5 | 2007-11-27 23:16:44 +0000 | [diff] [blame] | 206 | .. function:: warnpy3k(message[, category[, stacklevel]]) |
| 207 | |
| 208 | Issue a warning related to Python 3.x deprecation. Warnings are only shown |
Georg Brandl | 2b92f6b | 2007-12-06 01:52:24 +0000 | [diff] [blame] | 209 | when Python is started with the -3 option. Like :func:`warn` *message* must |
Christian Heimes | 28104c5 | 2007-11-27 23:16:44 +0000 | [diff] [blame] | 210 | be a string and *category* a subclass of :exc:`Warning`. :func:`warnpy3k` |
| 211 | is using :exc:`DeprecationWarning` as default warning class. |
| 212 | |
| 213 | |
Brett Cannon | e974689 | 2008-04-12 23:44:07 +0000 | [diff] [blame] | 214 | .. function:: showwarning(message, category, filename, lineno[, file[, line]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 215 | |
| 216 | Write a warning to a file. The default implementation calls |
Brett Cannon | e974689 | 2008-04-12 23:44:07 +0000 | [diff] [blame] | 217 | ``formatwarning(message, category, filename, lineno, line)`` and writes the |
| 218 | resulting string to *file*, which defaults to ``sys.stderr``. You may replace |
| 219 | this function with an alternative implementation by assigning to |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 220 | ``warnings.showwarning``. |
Andrew M. Kuchling | 311c580 | 2008-05-10 17:37:05 +0000 | [diff] [blame] | 221 | *line* is a line of source code to be included in the warning |
| 222 | message; if *line* is not supplied, :func:`showwarning` will |
| 223 | try to read the line specified by *filename* and *lineno*. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 224 | |
Georg Brandl | 4aa8df2 | 2008-04-13 07:07:44 +0000 | [diff] [blame] | 225 | .. versionchanged:: 2.6 |
Brett Cannon | 8a232cc | 2008-05-05 05:32:07 +0000 | [diff] [blame] | 226 | Added the *line* argument. Implementations that lack the new argument |
| 227 | will trigger a :exc:`DeprecationWarning`. |
Brett Cannon | e974689 | 2008-04-12 23:44:07 +0000 | [diff] [blame] | 228 | |
| 229 | |
| 230 | .. function:: formatwarning(message, category, filename, lineno[, line]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 231 | |
| 232 | Format a warning the standard way. This returns a string which may contain |
Andrew M. Kuchling | 311c580 | 2008-05-10 17:37:05 +0000 | [diff] [blame] | 233 | embedded newlines and ends in a newline. *line* is |
| 234 | a line of source code to be included in the warning message; if *line* is not supplied, |
| 235 | :func:`formatwarning` will try to read the line specified by *filename* and *lineno*. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 236 | |
Georg Brandl | 4aa8df2 | 2008-04-13 07:07:44 +0000 | [diff] [blame] | 237 | .. versionchanged:: 2.6 |
| 238 | Added the *line* argument. |
Brett Cannon | e974689 | 2008-04-12 23:44:07 +0000 | [diff] [blame] | 239 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 240 | |
| 241 | .. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]]) |
| 242 | |
| 243 | Insert an entry into the list of warnings filters. The entry is inserted at the |
| 244 | front by default; if *append* is true, it is inserted at the end. This checks |
| 245 | the types of the arguments, compiles the message and module regular expressions, |
| 246 | and inserts them as a tuple in the list of warnings filters. Entries closer to |
| 247 | the front of the list override entries later in the list, if both match a |
| 248 | particular warning. Omitted arguments default to a value that matches |
| 249 | everything. |
| 250 | |
| 251 | |
| 252 | .. function:: simplefilter(action[, category[, lineno[, append]]]) |
| 253 | |
| 254 | Insert a simple entry into the list of warnings filters. The meaning of the |
| 255 | function parameters is as for :func:`filterwarnings`, but regular expressions |
| 256 | are not needed as the filter inserted always matches any message in any module |
| 257 | as long as the category and line number match. |
| 258 | |
| 259 | |
| 260 | .. function:: resetwarnings() |
| 261 | |
| 262 | Reset the warnings filter. This discards the effect of all previous calls to |
| 263 | :func:`filterwarnings`, including that of the :option:`-W` command line options |
| 264 | and calls to :func:`simplefilter`. |
| 265 | |
Brett Cannon | 1eaf074 | 2008-09-02 01:25:16 +0000 | [diff] [blame] | 266 | |
| 267 | Available Classes |
| 268 | ----------------- |
| 269 | |
| 270 | .. class:: catch_warnings([record=False[, module=None]]) |
| 271 | |
Andrew M. Kuchling | 2dd647b | 2008-09-02 01:39:18 +0000 | [diff] [blame] | 272 | A context manager that guards the warnings filter from being permanently |
Brett Cannon | 1eaf074 | 2008-09-02 01:25:16 +0000 | [diff] [blame] | 273 | mutated. The manager returns an instance of :class:`WarningsRecorder`. The |
| 274 | *record* argument specifies whether warnings that would typically be |
| 275 | handled by :func:`showwarning` should instead be recorded by the |
| 276 | :class:`WarningsRecorder` instance. This argument is typically set when |
| 277 | testing for expected warnings behavior. The *module* argument may be a |
| 278 | module object that is to be used instead of the :mod:`warnings` module. |
| 279 | This argument should only be set when testing the :mod:`warnings` module |
| 280 | or some similar use-case. |
| 281 | |
| 282 | Typical usage of the context manager is like so:: |
| 283 | |
| 284 | def fxn(): |
| 285 | warn("fxn is deprecated", DeprecationWarning) |
| 286 | return "spam spam bacon spam" |
| 287 | |
| 288 | # The function 'fxn' is known to raise a DeprecationWarning. |
| 289 | with catch_warnings() as w: |
| 290 | warnings.filterwarning('ignore', 'fxn is deprecated', DeprecationWarning) |
| 291 | fxn() # DeprecationWarning is temporarily suppressed. |
| 292 | |
| 293 | .. note:: |
| 294 | |
| 295 | In Python 3.0, the arguments to the constructor for |
| 296 | :class:`catch_warnings` are keyword-only arguments. |
| 297 | |
| 298 | .. versionadded:: 2.6 |
| 299 | |
| 300 | |
| 301 | .. class:: WarningsRecorder() |
| 302 | |
| 303 | A subclass of :class:`list` that stores all warnings passed to |
| 304 | :func:`showwarning` when returned by a :class:`catch_warnings` context |
| 305 | manager created with its *record* argument set to ``True``. Each recorded |
| 306 | warning is represented by an object whose attributes correspond to the |
| 307 | arguments to :func:`showwarning`. As a convenience, a |
| 308 | :class:`WarningsRecorder` instance has the attributes of the last |
| 309 | recorded warning set on the :class:`WarningsRecorder` instance as well. |
| 310 | |
| 311 | .. method:: reset() |
| 312 | |
| 313 | Delete all recorded warnings. |
| 314 | |
| 315 | .. versionadded:: 2.6 |