blob: dbcf148995e9c1dbd107be16a6b707c99c4ffc50 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001: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
Éric Araujo29a0b572011-08-19 02:14:03 +020012**Source code:** :source:`Lib/warnings.py`
13
14--------------
15
Georg Brandl8ec7f652007-08-15 14:28:01 +000016Warning messages are typically issued in situations where it is useful to alert
17the user of some condition in a program, where that condition (normally) doesn't
18warrant raising an exception and terminating the program. For example, one
19might want to issue a warning when a program uses an obsolete module.
20
21Python programmers issue warnings by calling the :func:`warn` function defined
Benjamin Peterson092a1f72008-03-31 21:57:13 +000022in this module. (C programmers use :cfunc:`PyErr_WarnEx`; see
Georg Brandl8ec7f652007-08-15 14:28:01 +000023:ref:`exceptionhandling` for details).
24
25Warning messages are normally written to ``sys.stderr``, but their disposition
26can be changed flexibly, from ignoring all warnings to turning them into
27exceptions. The disposition of warnings can vary based on the warning category
28(see below), the text of the warning message, and the source location where it
29is issued. Repetitions of a particular warning for the same source location are
30typically suppressed.
31
32There are two stages in warning control: first, each time a warning is issued, a
33determination is made whether a message should be issued or not; next, if a
34message is to be issued, it is formatted and printed using a user-settable hook.
35
36The determination whether to issue a warning message is controlled by the
37warning filter, which is a sequence of matching rules and actions. Rules can be
38added to the filter by calling :func:`filterwarnings` and reset to its default
39state by calling :func:`resetwarnings`.
40
41The printing of warning messages is done by calling :func:`showwarning`, which
42may be overridden; the default implementation of this function formats the
43message by calling :func:`formatwarning`, which is also available for use by
44custom implementations.
45
Antoine Pitrou05045322011-07-09 21:29:36 +020046.. seealso::
47 :func:`logging.captureWarnings` allows you to handle all warnings with
48 the standard logging infrastructure.
49
Georg Brandl8ec7f652007-08-15 14:28:01 +000050
51.. _warning-categories:
52
53Warning Categories
54------------------
55
56There are a number of built-in exceptions that represent warning categories.
57This categorization is useful to be able to filter out groups of warnings. The
58following warnings category classes are currently defined:
59
60+----------------------------------+-----------------------------------------------+
61| Class | Description |
62+==================================+===============================================+
63| :exc:`Warning` | This is the base class of all warning |
64| | category classes. It is a subclass of |
65| | :exc:`Exception`. |
66+----------------------------------+-----------------------------------------------+
67| :exc:`UserWarning` | The default category for :func:`warn`. |
68+----------------------------------+-----------------------------------------------+
69| :exc:`DeprecationWarning` | Base category for warnings about deprecated |
Brett Cannon6fdd3dc2010-01-10 02:56:19 +000070| | features (ignored by default). |
Georg Brandl8ec7f652007-08-15 14:28:01 +000071+----------------------------------+-----------------------------------------------+
72| :exc:`SyntaxWarning` | Base category for warnings about dubious |
73| | syntactic features. |
74+----------------------------------+-----------------------------------------------+
75| :exc:`RuntimeWarning` | Base category for warnings about dubious |
76| | runtime features. |
77+----------------------------------+-----------------------------------------------+
78| :exc:`FutureWarning` | Base category for warnings about constructs |
79| | that will change semantically in the future. |
80+----------------------------------+-----------------------------------------------+
81| :exc:`PendingDeprecationWarning` | Base category for warnings about features |
82| | that will be deprecated in the future |
83| | (ignored by default). |
84+----------------------------------+-----------------------------------------------+
85| :exc:`ImportWarning` | Base category for warnings triggered during |
86| | the process of importing a module (ignored by |
87| | default). |
88+----------------------------------+-----------------------------------------------+
89| :exc:`UnicodeWarning` | Base category for warnings related to |
90| | Unicode. |
91+----------------------------------+-----------------------------------------------+
92
93While these are technically built-in exceptions, they are documented here,
94because conceptually they belong to the warnings mechanism.
95
96User code can define additional warning categories by subclassing one of the
97standard warning categories. A warning category must always be a subclass of
98the :exc:`Warning` class.
99
Brett Cannon6fdd3dc2010-01-10 02:56:19 +0000100.. versionchanged:: 2.7
101 :exc:`DeprecationWarning` is ignored by default.
102
Georg Brandl8ec7f652007-08-15 14:28:01 +0000103
104.. _warning-filter:
105
106The Warnings Filter
107-------------------
108
109The warnings filter controls whether warnings are ignored, displayed, or turned
110into errors (raising an exception).
111
112Conceptually, the warnings filter maintains an ordered list of filter
113specifications; any specific warning is matched against each filter
114specification in the list in turn until a match is found; the match determines
115the disposition of the match. Each entry is a tuple of the form (*action*,
116*message*, *category*, *module*, *lineno*), where:
117
118* *action* is one of the following strings:
119
120 +---------------+----------------------------------------------+
121 | Value | Disposition |
122 +===============+==============================================+
123 | ``"error"`` | turn matching warnings into exceptions |
124 +---------------+----------------------------------------------+
125 | ``"ignore"`` | never print matching warnings |
126 +---------------+----------------------------------------------+
127 | ``"always"`` | always print matching warnings |
128 +---------------+----------------------------------------------+
129 | ``"default"`` | print the first occurrence of matching |
130 | | warnings for each location where the warning |
131 | | is issued |
132 +---------------+----------------------------------------------+
133 | ``"module"`` | print the first occurrence of matching |
134 | | warnings for each module where the warning |
135 | | is issued |
136 +---------------+----------------------------------------------+
137 | ``"once"`` | print only the first occurrence of matching |
138 | | warnings, regardless of location |
139 +---------------+----------------------------------------------+
140
141* *message* is a string containing a regular expression that the warning message
Georg Brandlf0169702009-09-05 16:47:17 +0000142 must match (the match is compiled to always be case-insensitive).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000143
144* *category* is a class (a subclass of :exc:`Warning`) of which the warning
Georg Brandlf0169702009-09-05 16:47:17 +0000145 category must be a subclass in order to match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000146
147* *module* is a string containing a regular expression that the module name must
Georg Brandlf0169702009-09-05 16:47:17 +0000148 match (the match is compiled to be case-sensitive).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149
150* *lineno* is an integer that the line number where the warning occurred must
Georg Brandlf0169702009-09-05 16:47:17 +0000151 match, or ``0`` to match all line numbers.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000152
153Since the :exc:`Warning` class is derived from the built-in :exc:`Exception`
154class, to turn a warning into an error we simply raise ``category(message)``.
155
156The warnings filter is initialized by :option:`-W` options passed to the Python
157interpreter command line. The interpreter saves the arguments for all
158:option:`-W` options without interpretation in ``sys.warnoptions``; the
159:mod:`warnings` module parses these when it is first imported (invalid options
160are ignored, after printing a message to ``sys.stderr``).
161
Georg Brandl8ec7f652007-08-15 14:28:01 +0000162
Georg Brandl10603802010-11-26 08:10:41 +0000163Default Warning Filters
164~~~~~~~~~~~~~~~~~~~~~~~
165
166By default, Python installs several warning filters, which can be overridden by
167the command-line options passed to :option:`-W` and calls to
168:func:`filterwarnings`.
169
Georg Brandl241efde2010-11-26 08:58:14 +0000170* :exc:`PendingDeprecationWarning`, and :exc:`ImportWarning` are ignored.
Georg Brandl10603802010-11-26 08:10:41 +0000171
172* :exc:`BytesWarning` is ignored unless the :option:`-b` option is given once or
173 twice; in this case this warning is either printed (``-b``) or turned into an
Georg Brandl3b85b9b2010-11-26 08:20:18 +0000174 exception (``-bb``).
Georg Brandl10603802010-11-26 08:10:41 +0000175
Georg Brandl10603802010-11-26 08:10:41 +0000176
Brett Cannon672237d2008-09-09 00:49:16 +0000177.. _warning-suppress:
178
179Temporarily Suppressing Warnings
180--------------------------------
181
Nick Coghland2e09382008-09-11 12:11:06 +0000182If you are using code that you know will raise a warning, such as a deprecated
183function, but do not want to see the warning, then it is possible to suppress
184the warning using the :class:`catch_warnings` context manager::
Brett Cannon672237d2008-09-09 00:49:16 +0000185
186 import warnings
187
188 def fxn():
189 warnings.warn("deprecated", DeprecationWarning)
190
191 with warnings.catch_warnings():
192 warnings.simplefilter("ignore")
193 fxn()
194
195While within the context manager all warnings will simply be ignored. This
196allows you to use known-deprecated code without having to see the warning while
197not suppressing the warning for other code that might not be aware of its use
Andrew M. Kuchlingdc36d7c2010-04-02 17:54:26 +0000198of deprecated code. Note: this can only be guaranteed in a single-threaded
199application. If two or more threads use the :class:`catch_warnings` context
200manager at the same time, the behavior is undefined.
201
Brett Cannon672237d2008-09-09 00:49:16 +0000202
203
204.. _warning-testing:
205
206Testing Warnings
207----------------
208
209To test warnings raised by code, use the :class:`catch_warnings` context
210manager. With it you can temporarily mutate the warnings filter to facilitate
211your testing. For instance, do the following to capture all raised warnings to
212check::
213
214 import warnings
215
216 def fxn():
217 warnings.warn("deprecated", DeprecationWarning)
218
219 with warnings.catch_warnings(record=True) as w:
220 # Cause all warnings to always be triggered.
221 warnings.simplefilter("always")
222 # Trigger a warning.
223 fxn()
224 # Verify some things
225 assert len(w) == 1
Georg Brandlb4d0ef92009-07-18 09:03:10 +0000226 assert issubclass(w[-1].category, DeprecationWarning)
Brett Cannon672237d2008-09-09 00:49:16 +0000227 assert "deprecated" in str(w[-1].message)
228
229One can also cause all warnings to be exceptions by using ``error`` instead of
230``always``. One thing to be aware of is that if a warning has already been
231raised because of a ``once``/``default`` rule, then no matter what filters are
232set the warning will not be seen again unless the warnings registry related to
233the warning has been cleared.
234
235Once the context manager exits, the warnings filter is restored to its state
236when the context was entered. This prevents tests from changing the warnings
237filter in unexpected ways between tests and leading to indeterminate test
Nick Coghland2e09382008-09-11 12:11:06 +0000238results. The :func:`showwarning` function in the module is also restored to
Andrew M. Kuchlingdc36d7c2010-04-02 17:54:26 +0000239its original value. Note: this can only be guaranteed in a single-threaded
240application. If two or more threads use the :class:`catch_warnings` context
241manager at the same time, the behavior is undefined.
Nick Coghland2e09382008-09-11 12:11:06 +0000242
243When testing multiple operations that raise the same kind of warning, it
244is important to test them in a manner that confirms each operation is raising
245a new warning (e.g. set warnings to be raised as exceptions and check the
246operations raise exceptions, check that the length of the warning list
247continues to increase after each operation, or else delete the previous
248entries from the warnings list before each new operation).
Brett Cannon672237d2008-09-09 00:49:16 +0000249
250
Brett Cannon6fdd3dc2010-01-10 02:56:19 +0000251Updating Code For New Versions of Python
252----------------------------------------
253
254Warnings that are only of interest to the developer are ignored by default. As
255such you should make sure to test your code with typically ignored warnings
256made visible. You can do this from the command-line by passing :option:`-Wd`
257to the interpreter (this is shorthand for :option:`-W default`). This enables
258default handling for all warnings, including those that are ignored by default.
259To change what action is taken for encountered warnings you simply change what
260argument is passed to :option:`-W`, e.g. :option:`-W error`. See the
261:option:`-W` flag for more details on what is possible.
262
263To programmatically do the same as :option:`-Wd`, use::
264
265 warnings.simplefilter('default')
266
267Make sure to execute this code as soon as possible. This prevents the
268registering of what warnings have been raised from unexpectedly influencing how
269future warnings are treated.
270
271Having certain warnings ignored by default is done to prevent a user from
272seeing warnings that are only of interest to the developer. As you do not
273necessarily have control over what interpreter a user uses to run their code,
274it is possible that a new version of Python will be released between your
275release cycles. The new interpreter release could trigger new warnings in your
276code that were not there in an older interpreter, e.g.
277:exc:`DeprecationWarning` for a module that you are using. While you as a
278developer want to be notified that your code is using a deprecated module, to a
279user this information is essentially noise and provides no benefit to them.
280
281
Georg Brandl8ec7f652007-08-15 14:28:01 +0000282.. _warning-functions:
283
284Available Functions
285-------------------
286
287
288.. function:: warn(message[, category[, stacklevel]])
289
290 Issue a warning, or maybe ignore it or raise an exception. The *category*
291 argument, if given, must be a warning category class (see above); it defaults to
292 :exc:`UserWarning`. Alternatively *message* can be a :exc:`Warning` instance,
293 in which case *category* will be ignored and ``message.__class__`` will be used.
294 In this case the message text will be ``str(message)``. This function raises an
295 exception if the particular warning issued is changed into an error by the
296 warnings filter see above. The *stacklevel* argument can be used by wrapper
297 functions written in Python, like this::
298
299 def deprecation(message):
300 warnings.warn(message, DeprecationWarning, stacklevel=2)
301
302 This makes the warning refer to :func:`deprecation`'s caller, rather than to the
303 source of :func:`deprecation` itself (since the latter would defeat the purpose
304 of the warning message).
305
306
307.. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]])
308
309 This is a low-level interface to the functionality of :func:`warn`, passing in
310 explicitly the message, category, filename and line number, and optionally the
311 module name and the registry (which should be the ``__warningregistry__``
312 dictionary of the module). The module name defaults to the filename with
313 ``.py`` stripped; if no registry is passed, the warning is never suppressed.
314 *message* must be a string and *category* a subclass of :exc:`Warning` or
315 *message* may be a :exc:`Warning` instance, in which case *category* will be
316 ignored.
317
318 *module_globals*, if supplied, should be the global namespace in use by the code
319 for which the warning is issued. (This argument is used to support displaying
Brett Cannon338d4182007-12-09 05:09:37 +0000320 source for modules found in zipfiles or other non-filesystem import
321 sources).
322
323 .. versionchanged:: 2.5
Georg Brandl4aa8df22008-04-13 07:07:44 +0000324 Added the *module_globals* parameter.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000325
326
Christian Heimes28104c52007-11-27 23:16:44 +0000327.. function:: warnpy3k(message[, category[, stacklevel]])
328
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000329 Issue a warning related to Python 3.x deprecation. Warnings are only shown
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000330 when Python is started with the -3 option. Like :func:`warn` *message* must
Christian Heimes28104c52007-11-27 23:16:44 +0000331 be a string and *category* a subclass of :exc:`Warning`. :func:`warnpy3k`
332 is using :exc:`DeprecationWarning` as default warning class.
333
Benjamin Peterson72f94f72009-07-12 16:56:54 +0000334 .. versionadded:: 2.6
335
Christian Heimes28104c52007-11-27 23:16:44 +0000336
Brett Cannone9746892008-04-12 23:44:07 +0000337.. function:: showwarning(message, category, filename, lineno[, file[, line]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000338
339 Write a warning to a file. The default implementation calls
Brett Cannone9746892008-04-12 23:44:07 +0000340 ``formatwarning(message, category, filename, lineno, line)`` and writes the
341 resulting string to *file*, which defaults to ``sys.stderr``. You may replace
342 this function with an alternative implementation by assigning to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343 ``warnings.showwarning``.
Andrew M. Kuchling311c5802008-05-10 17:37:05 +0000344 *line* is a line of source code to be included in the warning
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000345 message; if *line* is not supplied, :func:`showwarning` will
Andrew M. Kuchling311c5802008-05-10 17:37:05 +0000346 try to read the line specified by *filename* and *lineno*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000347
Brett Cannon6c4cff02009-03-11 04:51:06 +0000348 .. versionchanged:: 2.7
349 The *line* argument is required to be supported.
Brett Cannone9746892008-04-12 23:44:07 +0000350
351
352.. function:: formatwarning(message, category, filename, lineno[, line])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000353
Georg Brandlf0169702009-09-05 16:47:17 +0000354 Format a warning the standard way. This returns a string which may contain
355 embedded newlines and ends in a newline. *line* is a line of source code to
356 be included in the warning message; if *line* is not supplied,
357 :func:`formatwarning` will try to read the line specified by *filename* and
358 *lineno*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000359
Georg Brandl4aa8df22008-04-13 07:07:44 +0000360 .. versionchanged:: 2.6
361 Added the *line* argument.
Brett Cannone9746892008-04-12 23:44:07 +0000362
Georg Brandl8ec7f652007-08-15 14:28:01 +0000363
364.. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]])
365
Georg Brandlf0169702009-09-05 16:47:17 +0000366 Insert an entry into the list of :ref:`warnings filter specifications
367 <warning-filter>`. The entry is inserted at the front by default; if
368 *append* is true, it is inserted at the end. This checks the types of the
369 arguments, compiles the *message* and *module* regular expressions, and
370 inserts them as a tuple in the list of warnings filters. Entries closer to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000371 the front of the list override entries later in the list, if both match a
372 particular warning. Omitted arguments default to a value that matches
373 everything.
374
375
376.. function:: simplefilter(action[, category[, lineno[, append]]])
377
Georg Brandlf0169702009-09-05 16:47:17 +0000378 Insert a simple entry into the list of :ref:`warnings filter specifications
379 <warning-filter>`. The meaning of the function parameters is as for
380 :func:`filterwarnings`, but regular expressions are not needed as the filter
381 inserted always matches any message in any module as long as the category and
382 line number match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000383
384
385.. function:: resetwarnings()
386
387 Reset the warnings filter. This discards the effect of all previous calls to
388 :func:`filterwarnings`, including that of the :option:`-W` command line options
389 and calls to :func:`simplefilter`.
390
Brett Cannon1eaf0742008-09-02 01:25:16 +0000391
Brett Cannon672237d2008-09-09 00:49:16 +0000392Available Context Managers
393--------------------------
Brett Cannon1eaf0742008-09-02 01:25:16 +0000394
Brett Cannon672237d2008-09-09 00:49:16 +0000395.. class:: catch_warnings([\*, record=False, module=None])
Brett Cannon1eaf0742008-09-02 01:25:16 +0000396
Nick Coghland2e09382008-09-11 12:11:06 +0000397 A context manager that copies and, upon exit, restores the warnings filter
398 and the :func:`showwarning` function.
399 If the *record* argument is :const:`False` (the default) the context manager
400 returns :class:`None` on entry. If *record* is :const:`True`, a list is
401 returned that is progressively populated with objects as seen by a custom
402 :func:`showwarning` function (which also suppresses output to ``sys.stdout``).
403 Each object in the list has attributes with the same names as the arguments to
404 :func:`showwarning`.
Brett Cannon1eaf0742008-09-02 01:25:16 +0000405
Brett Cannon672237d2008-09-09 00:49:16 +0000406 The *module* argument takes a module that will be used instead of the
407 module returned when you import :mod:`warnings` whose filter will be
Nick Coghland2e09382008-09-11 12:11:06 +0000408 protected. This argument exists primarily for testing the :mod:`warnings`
Brett Cannon672237d2008-09-09 00:49:16 +0000409 module itself.
Brett Cannon1eaf0742008-09-02 01:25:16 +0000410
411 .. note::
412
Andrew M. Kuchlingd8862902010-04-02 17:48:23 +0000413 The :class:`catch_warnings` manager works by replacing and
414 then later restoring the module's
415 :func:`showwarning` function and internal list of filter
416 specifications. This means the context manager is modifying
417 global state and therefore is not thread-safe.
418
419 .. note::
420
Brett Cannon1eaf0742008-09-02 01:25:16 +0000421 In Python 3.0, the arguments to the constructor for
422 :class:`catch_warnings` are keyword-only arguments.
423
424 .. versionadded:: 2.6
425