Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | :mod:`warnings` --- Warning control |
| 2 | =================================== |
| 3 | |
| 4 | .. index:: single: warnings |
| 5 | |
| 6 | .. module:: warnings |
| 7 | :synopsis: Issue warning messages and control their disposition. |
| 8 | |
| 9 | |
| 10 | .. versionadded:: 2.1 |
| 11 | |
| 12 | Warning messages are typically issued in situations where it is useful to alert |
| 13 | the user of some condition in a program, where that condition (normally) doesn't |
| 14 | warrant raising an exception and terminating the program. For example, one |
| 15 | might want to issue a warning when a program uses an obsolete module. |
| 16 | |
| 17 | Python programmers issue warnings by calling the :func:`warn` function defined |
Benjamin Peterson | 092a1f7 | 2008-03-31 21:57:13 +0000 | [diff] [blame] | 18 | in this module. (C programmers use :cfunc:`PyErr_WarnEx`; see |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 19 | :ref:`exceptionhandling` for details). |
| 20 | |
| 21 | Warning messages are normally written to ``sys.stderr``, but their disposition |
| 22 | can be changed flexibly, from ignoring all warnings to turning them into |
| 23 | exceptions. The disposition of warnings can vary based on the warning category |
| 24 | (see below), the text of the warning message, and the source location where it |
| 25 | is issued. Repetitions of a particular warning for the same source location are |
| 26 | typically suppressed. |
| 27 | |
| 28 | There are two stages in warning control: first, each time a warning is issued, a |
| 29 | determination is made whether a message should be issued or not; next, if a |
| 30 | message is to be issued, it is formatted and printed using a user-settable hook. |
| 31 | |
| 32 | The determination whether to issue a warning message is controlled by the |
| 33 | warning filter, which is a sequence of matching rules and actions. Rules can be |
| 34 | added to the filter by calling :func:`filterwarnings` and reset to its default |
| 35 | state by calling :func:`resetwarnings`. |
| 36 | |
| 37 | The printing of warning messages is done by calling :func:`showwarning`, which |
| 38 | may be overridden; the default implementation of this function formats the |
| 39 | message by calling :func:`formatwarning`, which is also available for use by |
| 40 | custom implementations. |
| 41 | |
| 42 | |
| 43 | .. _warning-categories: |
| 44 | |
| 45 | Warning Categories |
| 46 | ------------------ |
| 47 | |
| 48 | There are a number of built-in exceptions that represent warning categories. |
| 49 | This categorization is useful to be able to filter out groups of warnings. The |
| 50 | following warnings category classes are currently defined: |
| 51 | |
| 52 | +----------------------------------+-----------------------------------------------+ |
| 53 | | Class | Description | |
| 54 | +==================================+===============================================+ |
| 55 | | :exc:`Warning` | This is the base class of all warning | |
| 56 | | | category classes. It is a subclass of | |
| 57 | | | :exc:`Exception`. | |
| 58 | +----------------------------------+-----------------------------------------------+ |
| 59 | | :exc:`UserWarning` | The default category for :func:`warn`. | |
| 60 | +----------------------------------+-----------------------------------------------+ |
| 61 | | :exc:`DeprecationWarning` | Base category for warnings about deprecated | |
| 62 | | | features. | |
| 63 | +----------------------------------+-----------------------------------------------+ |
| 64 | | :exc:`SyntaxWarning` | Base category for warnings about dubious | |
| 65 | | | syntactic features. | |
| 66 | +----------------------------------+-----------------------------------------------+ |
| 67 | | :exc:`RuntimeWarning` | Base category for warnings about dubious | |
| 68 | | | runtime features. | |
| 69 | +----------------------------------+-----------------------------------------------+ |
| 70 | | :exc:`FutureWarning` | Base category for warnings about constructs | |
| 71 | | | that will change semantically in the future. | |
| 72 | +----------------------------------+-----------------------------------------------+ |
| 73 | | :exc:`PendingDeprecationWarning` | Base category for warnings about features | |
| 74 | | | that will be deprecated in the future | |
| 75 | | | (ignored by default). | |
| 76 | +----------------------------------+-----------------------------------------------+ |
| 77 | | :exc:`ImportWarning` | Base category for warnings triggered during | |
| 78 | | | the process of importing a module (ignored by | |
| 79 | | | default). | |
| 80 | +----------------------------------+-----------------------------------------------+ |
| 81 | | :exc:`UnicodeWarning` | Base category for warnings related to | |
| 82 | | | Unicode. | |
| 83 | +----------------------------------+-----------------------------------------------+ |
| 84 | |
| 85 | While these are technically built-in exceptions, they are documented here, |
| 86 | because conceptually they belong to the warnings mechanism. |
| 87 | |
| 88 | User code can define additional warning categories by subclassing one of the |
| 89 | standard warning categories. A warning category must always be a subclass of |
| 90 | the :exc:`Warning` class. |
| 91 | |
| 92 | |
| 93 | .. _warning-filter: |
| 94 | |
| 95 | The Warnings Filter |
| 96 | ------------------- |
| 97 | |
| 98 | The warnings filter controls whether warnings are ignored, displayed, or turned |
| 99 | into errors (raising an exception). |
| 100 | |
| 101 | Conceptually, the warnings filter maintains an ordered list of filter |
| 102 | specifications; any specific warning is matched against each filter |
| 103 | specification in the list in turn until a match is found; the match determines |
| 104 | the disposition of the match. Each entry is a tuple of the form (*action*, |
| 105 | *message*, *category*, *module*, *lineno*), where: |
| 106 | |
| 107 | * *action* is one of the following strings: |
| 108 | |
| 109 | +---------------+----------------------------------------------+ |
| 110 | | Value | Disposition | |
| 111 | +===============+==============================================+ |
| 112 | | ``"error"`` | turn matching warnings into exceptions | |
| 113 | +---------------+----------------------------------------------+ |
| 114 | | ``"ignore"`` | never print matching warnings | |
| 115 | +---------------+----------------------------------------------+ |
| 116 | | ``"always"`` | always print matching warnings | |
| 117 | +---------------+----------------------------------------------+ |
| 118 | | ``"default"`` | print the first occurrence of matching | |
| 119 | | | warnings for each location where the warning | |
| 120 | | | is issued | |
| 121 | +---------------+----------------------------------------------+ |
| 122 | | ``"module"`` | print the first occurrence of matching | |
| 123 | | | warnings for each module where the warning | |
| 124 | | | is issued | |
| 125 | +---------------+----------------------------------------------+ |
| 126 | | ``"once"`` | print only the first occurrence of matching | |
| 127 | | | warnings, regardless of location | |
| 128 | +---------------+----------------------------------------------+ |
| 129 | |
| 130 | * *message* is a string containing a regular expression that the warning message |
Georg Brandl | f016970 | 2009-09-05 16:47:17 +0000 | [diff] [blame] | 131 | must match (the match is compiled to always be case-insensitive). |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 132 | |
| 133 | * *category* is a class (a subclass of :exc:`Warning`) of which the warning |
Georg Brandl | f016970 | 2009-09-05 16:47:17 +0000 | [diff] [blame] | 134 | category must be a subclass in order to match. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 135 | |
| 136 | * *module* is a string containing a regular expression that the module name must |
Georg Brandl | f016970 | 2009-09-05 16:47:17 +0000 | [diff] [blame] | 137 | match (the match is compiled to be case-sensitive). |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 138 | |
| 139 | * *lineno* is an integer that the line number where the warning occurred must |
Georg Brandl | f016970 | 2009-09-05 16:47:17 +0000 | [diff] [blame] | 140 | match, or ``0`` to match all line numbers. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 141 | |
| 142 | Since the :exc:`Warning` class is derived from the built-in :exc:`Exception` |
| 143 | class, to turn a warning into an error we simply raise ``category(message)``. |
| 144 | |
| 145 | The warnings filter is initialized by :option:`-W` options passed to the Python |
| 146 | interpreter command line. The interpreter saves the arguments for all |
| 147 | :option:`-W` options without interpretation in ``sys.warnoptions``; the |
| 148 | :mod:`warnings` module parses these when it is first imported (invalid options |
| 149 | are ignored, after printing a message to ``sys.stderr``). |
| 150 | |
| 151 | The warnings that are ignored by default may be enabled by passing :option:`-Wd` |
| 152 | to the interpreter. This enables default handling for all warnings, including |
| 153 | those that are normally ignored by default. This is particular useful for |
| 154 | enabling ImportWarning when debugging problems importing a developed package. |
| 155 | ImportWarning can also be enabled explicitly in Python code using:: |
| 156 | |
| 157 | warnings.simplefilter('default', ImportWarning) |
| 158 | |
| 159 | |
Brett Cannon | 672237d | 2008-09-09 00:49:16 +0000 | [diff] [blame] | 160 | .. _warning-suppress: |
| 161 | |
| 162 | Temporarily Suppressing Warnings |
| 163 | -------------------------------- |
| 164 | |
Nick Coghlan | d2e0938 | 2008-09-11 12:11:06 +0000 | [diff] [blame] | 165 | If you are using code that you know will raise a warning, such as a deprecated |
| 166 | function, but do not want to see the warning, then it is possible to suppress |
| 167 | the warning using the :class:`catch_warnings` context manager:: |
Brett Cannon | 672237d | 2008-09-09 00:49:16 +0000 | [diff] [blame] | 168 | |
| 169 | import warnings |
| 170 | |
| 171 | def fxn(): |
| 172 | warnings.warn("deprecated", DeprecationWarning) |
| 173 | |
| 174 | with warnings.catch_warnings(): |
| 175 | warnings.simplefilter("ignore") |
| 176 | fxn() |
| 177 | |
| 178 | While within the context manager all warnings will simply be ignored. This |
| 179 | allows you to use known-deprecated code without having to see the warning while |
| 180 | not suppressing the warning for other code that might not be aware of its use |
| 181 | of deprecated code. |
| 182 | |
| 183 | |
| 184 | .. _warning-testing: |
| 185 | |
| 186 | Testing Warnings |
| 187 | ---------------- |
| 188 | |
| 189 | To test warnings raised by code, use the :class:`catch_warnings` context |
| 190 | manager. With it you can temporarily mutate the warnings filter to facilitate |
| 191 | your testing. For instance, do the following to capture all raised warnings to |
| 192 | check:: |
| 193 | |
| 194 | import warnings |
| 195 | |
| 196 | def fxn(): |
| 197 | warnings.warn("deprecated", DeprecationWarning) |
| 198 | |
| 199 | with warnings.catch_warnings(record=True) as w: |
| 200 | # Cause all warnings to always be triggered. |
| 201 | warnings.simplefilter("always") |
| 202 | # Trigger a warning. |
| 203 | fxn() |
| 204 | # Verify some things |
| 205 | assert len(w) == 1 |
Georg Brandl | b4d0ef9 | 2009-07-18 09:03:10 +0000 | [diff] [blame] | 206 | assert issubclass(w[-1].category, DeprecationWarning) |
Brett Cannon | 672237d | 2008-09-09 00:49:16 +0000 | [diff] [blame] | 207 | assert "deprecated" in str(w[-1].message) |
| 208 | |
| 209 | One can also cause all warnings to be exceptions by using ``error`` instead of |
| 210 | ``always``. One thing to be aware of is that if a warning has already been |
| 211 | raised because of a ``once``/``default`` rule, then no matter what filters are |
| 212 | set the warning will not be seen again unless the warnings registry related to |
| 213 | the warning has been cleared. |
| 214 | |
| 215 | Once the context manager exits, the warnings filter is restored to its state |
| 216 | when the context was entered. This prevents tests from changing the warnings |
| 217 | filter in unexpected ways between tests and leading to indeterminate test |
Nick Coghlan | d2e0938 | 2008-09-11 12:11:06 +0000 | [diff] [blame] | 218 | results. The :func:`showwarning` function in the module is also restored to |
| 219 | its original value. |
| 220 | |
| 221 | When testing multiple operations that raise the same kind of warning, it |
| 222 | is important to test them in a manner that confirms each operation is raising |
| 223 | a new warning (e.g. set warnings to be raised as exceptions and check the |
| 224 | operations raise exceptions, check that the length of the warning list |
| 225 | continues to increase after each operation, or else delete the previous |
| 226 | entries from the warnings list before each new operation). |
Brett Cannon | 672237d | 2008-09-09 00:49:16 +0000 | [diff] [blame] | 227 | |
| 228 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 229 | .. _warning-functions: |
| 230 | |
| 231 | Available Functions |
| 232 | ------------------- |
| 233 | |
| 234 | |
| 235 | .. function:: warn(message[, category[, stacklevel]]) |
| 236 | |
| 237 | Issue a warning, or maybe ignore it or raise an exception. The *category* |
| 238 | argument, if given, must be a warning category class (see above); it defaults to |
| 239 | :exc:`UserWarning`. Alternatively *message* can be a :exc:`Warning` instance, |
| 240 | in which case *category* will be ignored and ``message.__class__`` will be used. |
| 241 | In this case the message text will be ``str(message)``. This function raises an |
| 242 | exception if the particular warning issued is changed into an error by the |
| 243 | warnings filter see above. The *stacklevel* argument can be used by wrapper |
| 244 | functions written in Python, like this:: |
| 245 | |
| 246 | def deprecation(message): |
| 247 | warnings.warn(message, DeprecationWarning, stacklevel=2) |
| 248 | |
| 249 | This makes the warning refer to :func:`deprecation`'s caller, rather than to the |
| 250 | source of :func:`deprecation` itself (since the latter would defeat the purpose |
| 251 | of the warning message). |
| 252 | |
| 253 | |
| 254 | .. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]]) |
| 255 | |
| 256 | This is a low-level interface to the functionality of :func:`warn`, passing in |
| 257 | explicitly the message, category, filename and line number, and optionally the |
| 258 | module name and the registry (which should be the ``__warningregistry__`` |
| 259 | dictionary of the module). The module name defaults to the filename with |
| 260 | ``.py`` stripped; if no registry is passed, the warning is never suppressed. |
| 261 | *message* must be a string and *category* a subclass of :exc:`Warning` or |
| 262 | *message* may be a :exc:`Warning` instance, in which case *category* will be |
| 263 | ignored. |
| 264 | |
| 265 | *module_globals*, if supplied, should be the global namespace in use by the code |
| 266 | 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] | 267 | source for modules found in zipfiles or other non-filesystem import |
| 268 | sources). |
| 269 | |
| 270 | .. versionchanged:: 2.5 |
Georg Brandl | 4aa8df2 | 2008-04-13 07:07:44 +0000 | [diff] [blame] | 271 | Added the *module_globals* parameter. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 272 | |
| 273 | |
Christian Heimes | 28104c5 | 2007-11-27 23:16:44 +0000 | [diff] [blame] | 274 | .. function:: warnpy3k(message[, category[, stacklevel]]) |
| 275 | |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 276 | 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] | 277 | 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] | 278 | be a string and *category* a subclass of :exc:`Warning`. :func:`warnpy3k` |
| 279 | is using :exc:`DeprecationWarning` as default warning class. |
| 280 | |
Benjamin Peterson | 72f94f7 | 2009-07-12 16:56:54 +0000 | [diff] [blame] | 281 | .. versionadded:: 2.6 |
| 282 | |
Christian Heimes | 28104c5 | 2007-11-27 23:16:44 +0000 | [diff] [blame] | 283 | |
Brett Cannon | e974689 | 2008-04-12 23:44:07 +0000 | [diff] [blame] | 284 | .. function:: showwarning(message, category, filename, lineno[, file[, line]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 285 | |
| 286 | Write a warning to a file. The default implementation calls |
Brett Cannon | e974689 | 2008-04-12 23:44:07 +0000 | [diff] [blame] | 287 | ``formatwarning(message, category, filename, lineno, line)`` and writes the |
| 288 | resulting string to *file*, which defaults to ``sys.stderr``. You may replace |
| 289 | this function with an alternative implementation by assigning to |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 290 | ``warnings.showwarning``. |
Andrew M. Kuchling | 311c580 | 2008-05-10 17:37:05 +0000 | [diff] [blame] | 291 | *line* is a line of source code to be included in the warning |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 292 | message; if *line* is not supplied, :func:`showwarning` will |
Andrew M. Kuchling | 311c580 | 2008-05-10 17:37:05 +0000 | [diff] [blame] | 293 | try to read the line specified by *filename* and *lineno*. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 294 | |
Brett Cannon | 6c4cff0 | 2009-03-11 04:51:06 +0000 | [diff] [blame] | 295 | .. versionchanged:: 2.7 |
| 296 | The *line* argument is required to be supported. |
Brett Cannon | e974689 | 2008-04-12 23:44:07 +0000 | [diff] [blame] | 297 | |
| 298 | |
| 299 | .. function:: formatwarning(message, category, filename, lineno[, line]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 300 | |
Georg Brandl | f016970 | 2009-09-05 16:47:17 +0000 | [diff] [blame] | 301 | Format a warning the standard way. This returns a string which may contain |
| 302 | embedded newlines and ends in a newline. *line* is a line of source code to |
| 303 | be included in the warning message; if *line* is not supplied, |
| 304 | :func:`formatwarning` will try to read the line specified by *filename* and |
| 305 | *lineno*. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 306 | |
Georg Brandl | 4aa8df2 | 2008-04-13 07:07:44 +0000 | [diff] [blame] | 307 | .. versionchanged:: 2.6 |
| 308 | Added the *line* argument. |
Brett Cannon | e974689 | 2008-04-12 23:44:07 +0000 | [diff] [blame] | 309 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 310 | |
| 311 | .. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]]) |
| 312 | |
Georg Brandl | f016970 | 2009-09-05 16:47:17 +0000 | [diff] [blame] | 313 | Insert an entry into the list of :ref:`warnings filter specifications |
| 314 | <warning-filter>`. The entry is inserted at the front by default; if |
| 315 | *append* is true, it is inserted at the end. This checks the types of the |
| 316 | arguments, compiles the *message* and *module* regular expressions, and |
| 317 | inserts them as a tuple in the list of warnings filters. Entries closer to |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 318 | the front of the list override entries later in the list, if both match a |
| 319 | particular warning. Omitted arguments default to a value that matches |
| 320 | everything. |
| 321 | |
| 322 | |
| 323 | .. function:: simplefilter(action[, category[, lineno[, append]]]) |
| 324 | |
Georg Brandl | f016970 | 2009-09-05 16:47:17 +0000 | [diff] [blame] | 325 | Insert a simple entry into the list of :ref:`warnings filter specifications |
| 326 | <warning-filter>`. The meaning of the function parameters is as for |
| 327 | :func:`filterwarnings`, but regular expressions are not needed as the filter |
| 328 | inserted always matches any message in any module as long as the category and |
| 329 | line number match. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 330 | |
| 331 | |
| 332 | .. function:: resetwarnings() |
| 333 | |
| 334 | Reset the warnings filter. This discards the effect of all previous calls to |
| 335 | :func:`filterwarnings`, including that of the :option:`-W` command line options |
| 336 | and calls to :func:`simplefilter`. |
| 337 | |
Brett Cannon | 1eaf074 | 2008-09-02 01:25:16 +0000 | [diff] [blame] | 338 | |
Brett Cannon | 672237d | 2008-09-09 00:49:16 +0000 | [diff] [blame] | 339 | Available Context Managers |
| 340 | -------------------------- |
Brett Cannon | 1eaf074 | 2008-09-02 01:25:16 +0000 | [diff] [blame] | 341 | |
Brett Cannon | 672237d | 2008-09-09 00:49:16 +0000 | [diff] [blame] | 342 | .. class:: catch_warnings([\*, record=False, module=None]) |
Brett Cannon | 1eaf074 | 2008-09-02 01:25:16 +0000 | [diff] [blame] | 343 | |
Nick Coghlan | d2e0938 | 2008-09-11 12:11:06 +0000 | [diff] [blame] | 344 | A context manager that copies and, upon exit, restores the warnings filter |
| 345 | and the :func:`showwarning` function. |
| 346 | If the *record* argument is :const:`False` (the default) the context manager |
| 347 | returns :class:`None` on entry. If *record* is :const:`True`, a list is |
| 348 | returned that is progressively populated with objects as seen by a custom |
| 349 | :func:`showwarning` function (which also suppresses output to ``sys.stdout``). |
| 350 | Each object in the list has attributes with the same names as the arguments to |
| 351 | :func:`showwarning`. |
Brett Cannon | 1eaf074 | 2008-09-02 01:25:16 +0000 | [diff] [blame] | 352 | |
Brett Cannon | 672237d | 2008-09-09 00:49:16 +0000 | [diff] [blame] | 353 | The *module* argument takes a module that will be used instead of the |
| 354 | module returned when you import :mod:`warnings` whose filter will be |
Nick Coghlan | d2e0938 | 2008-09-11 12:11:06 +0000 | [diff] [blame] | 355 | protected. This argument exists primarily for testing the :mod:`warnings` |
Brett Cannon | 672237d | 2008-09-09 00:49:16 +0000 | [diff] [blame] | 356 | module itself. |
Brett Cannon | 1eaf074 | 2008-09-02 01:25:16 +0000 | [diff] [blame] | 357 | |
| 358 | .. note:: |
| 359 | |
| 360 | In Python 3.0, the arguments to the constructor for |
| 361 | :class:`catch_warnings` are keyword-only arguments. |
| 362 | |
| 363 | .. versionadded:: 2.6 |
| 364 | |