blob: 274840b342a3ef0edd2c78c3e66dfae3ea05241a [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Raymond Hettinger469271d2011-01-27 20:38:46 +00009**Source code:** :source:`Lib/warnings.py`
10
11--------------
Georg Brandl116aa622007-08-15 14:28:22 +000012
Georg Brandl116aa622007-08-15 14:28:22 +000013Warning messages are typically issued in situations where it is useful to alert
14the user of some condition in a program, where that condition (normally) doesn't
15warrant raising an exception and terminating the program. For example, one
16might want to issue a warning when a program uses an obsolete module.
17
18Python programmers issue warnings by calling the :func:`warn` function defined
Georg Brandl60203b42010-10-06 10:11:56 +000019in this module. (C programmers use :c:func:`PyErr_WarnEx`; see
Georg Brandl116aa622007-08-15 14:28:22 +000020:ref:`exceptionhandling` for details).
21
22Warning messages are normally written to ``sys.stderr``, but their disposition
23can be changed flexibly, from ignoring all warnings to turning them into
24exceptions. 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
26is issued. Repetitions of a particular warning for the same source location are
27typically suppressed.
28
29There are two stages in warning control: first, each time a warning is issued, a
30determination is made whether a message should be issued or not; next, if a
31message is to be issued, it is formatted and printed using a user-settable hook.
32
33The determination whether to issue a warning message is controlled by the
34warning filter, which is a sequence of matching rules and actions. Rules can be
35added to the filter by calling :func:`filterwarnings` and reset to its default
36state by calling :func:`resetwarnings`.
37
38The printing of warning messages is done by calling :func:`showwarning`, which
39may be overridden; the default implementation of this function formats the
40message by calling :func:`formatwarning`, which is also available for use by
41custom implementations.
42
43
44.. _warning-categories:
45
46Warning Categories
47------------------
48
49There are a number of built-in exceptions that represent warning categories.
50This categorization is useful to be able to filter out groups of warnings. The
51following 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 |
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +000063| | features (ignored by default). |
Georg Brandl116aa622007-08-15 14:28:22 +000064+----------------------------------+-----------------------------------------------+
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+----------------------------------+-----------------------------------------------+
Guido van Rossum98297ee2007-11-06 21:34:58 +000085| :exc:`BytesWarning` | Base category for warnings related to |
86| | :class:`bytes` and :class:`buffer`. |
87+----------------------------------+-----------------------------------------------+
Georg Brandl08be72d2010-10-24 15:11:22 +000088| :exc:`ResourceWarning` | Base category for warnings related to |
89| | resource usage. |
90+----------------------------------+-----------------------------------------------+
Guido van Rossum98297ee2007-11-06 21:34:58 +000091
Georg Brandl116aa622007-08-15 14:28:22 +000092
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
100
101.. _warning-filter:
102
103The Warnings Filter
104-------------------
105
106The warnings filter controls whether warnings are ignored, displayed, or turned
107into errors (raising an exception).
108
109Conceptually, the warnings filter maintains an ordered list of filter
110specifications; any specific warning is matched against each filter
111specification in the list in turn until a match is found; the match determines
112the disposition of the match. Each entry is a tuple of the form (*action*,
113*message*, *category*, *module*, *lineno*), where:
114
115* *action* is one of the following strings:
116
117 +---------------+----------------------------------------------+
118 | Value | Disposition |
119 +===============+==============================================+
120 | ``"error"`` | turn matching warnings into exceptions |
121 +---------------+----------------------------------------------+
122 | ``"ignore"`` | never print matching warnings |
123 +---------------+----------------------------------------------+
124 | ``"always"`` | always print matching warnings |
125 +---------------+----------------------------------------------+
126 | ``"default"`` | print the first occurrence of matching |
127 | | warnings for each location where the warning |
128 | | is issued |
129 +---------------+----------------------------------------------+
130 | ``"module"`` | print the first occurrence of matching |
131 | | warnings for each module where the warning |
132 | | is issued |
133 +---------------+----------------------------------------------+
134 | ``"once"`` | print only the first occurrence of matching |
135 | | warnings, regardless of location |
136 +---------------+----------------------------------------------+
137
138* *message* is a string containing a regular expression that the warning message
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000139 must match (the match is compiled to always be case-insensitive).
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141* *category* is a class (a subclass of :exc:`Warning`) of which the warning
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000142 category must be a subclass in order to match.
Georg Brandl116aa622007-08-15 14:28:22 +0000143
144* *module* is a string containing a regular expression that the module name must
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000145 match (the match is compiled to be case-sensitive).
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147* *lineno* is an integer that the line number where the warning occurred must
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000148 match, or ``0`` to match all line numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150Since the :exc:`Warning` class is derived from the built-in :exc:`Exception`
151class, to turn a warning into an error we simply raise ``category(message)``.
152
153The warnings filter is initialized by :option:`-W` options passed to the Python
154interpreter command line. The interpreter saves the arguments for all
155:option:`-W` options without interpretation in ``sys.warnoptions``; the
156:mod:`warnings` module parses these when it is first imported (invalid options
157are ignored, after printing a message to ``sys.stderr``).
158
Georg Brandl116aa622007-08-15 14:28:22 +0000159
Georg Brandl20629372010-10-24 15:16:02 +0000160Default Warning Filters
161~~~~~~~~~~~~~~~~~~~~~~~
162
163By default, Python installs several warning filters, which can be overridden by
164the command-line options passed to :option:`-W` and calls to
165:func:`filterwarnings`.
166
167* :exc:`DeprecationWarning` and :exc:`PendingDeprecationWarning`, and
168 :exc:`ImportWarning` are ignored.
169
170* :exc:`BytesWarning` is ignored unless the :option:`-b` option is given once or
171 twice; in this case this warning is either printed (``-b``) or turned into an
Georg Brandl19208902010-10-26 06:59:23 +0000172 exception (``-bb``).
Georg Brandl20629372010-10-24 15:16:02 +0000173
174* :exc:`ResourceWarning` is ignored unless Python was built in debug mode.
175
176.. versionchanged:: 3.2
177 :exc:`DeprecationWarning` is now ignored by default in addition to
178 :exc:`PendingDeprecationWarning`.
179
180
Brett Cannon1cd02472008-09-09 01:52:27 +0000181.. _warning-suppress:
182
183Temporarily Suppressing Warnings
184--------------------------------
185
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000186If you are using code that you know will raise a warning, such as a deprecated
187function, but do not want to see the warning, then it is possible to suppress
188the warning using the :class:`catch_warnings` context manager::
Brett Cannon1cd02472008-09-09 01:52:27 +0000189
190 import warnings
191
192 def fxn():
193 warnings.warn("deprecated", DeprecationWarning)
194
195 with warnings.catch_warnings():
196 warnings.simplefilter("ignore")
197 fxn()
198
199While within the context manager all warnings will simply be ignored. This
200allows you to use known-deprecated code without having to see the warning while
201not suppressing the warning for other code that might not be aware of its use
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000202of deprecated code. Note: this can only be guaranteed in a single-threaded
203application. If two or more threads use the :class:`catch_warnings` context
204manager at the same time, the behavior is undefined.
205
Brett Cannon1cd02472008-09-09 01:52:27 +0000206
207
208.. _warning-testing:
209
210Testing Warnings
211----------------
212
213To test warnings raised by code, use the :class:`catch_warnings` context
214manager. With it you can temporarily mutate the warnings filter to facilitate
215your testing. For instance, do the following to capture all raised warnings to
216check::
217
218 import warnings
219
220 def fxn():
221 warnings.warn("deprecated", DeprecationWarning)
222
223 with warnings.catch_warnings(record=True) as w:
224 # Cause all warnings to always be triggered.
225 warnings.simplefilter("always")
226 # Trigger a warning.
227 fxn()
228 # Verify some things
229 assert len(w) == 1
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000230 assert issubclass(w[-1].category, DeprecationWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000231 assert "deprecated" in str(w[-1].message)
232
233One can also cause all warnings to be exceptions by using ``error`` instead of
234``always``. One thing to be aware of is that if a warning has already been
235raised because of a ``once``/``default`` rule, then no matter what filters are
236set the warning will not be seen again unless the warnings registry related to
237the warning has been cleared.
238
239Once the context manager exits, the warnings filter is restored to its state
240when the context was entered. This prevents tests from changing the warnings
241filter in unexpected ways between tests and leading to indeterminate test
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000242results. The :func:`showwarning` function in the module is also restored to
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000243its original value. Note: this can only be guaranteed in a single-threaded
244application. If two or more threads use the :class:`catch_warnings` context
245manager at the same time, the behavior is undefined.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000246
247When testing multiple operations that raise the same kind of warning, it
248is important to test them in a manner that confirms each operation is raising
249a new warning (e.g. set warnings to be raised as exceptions and check the
250operations raise exceptions, check that the length of the warning list
251continues to increase after each operation, or else delete the previous
252entries from the warnings list before each new operation).
Brett Cannon1cd02472008-09-09 01:52:27 +0000253
254
Ezio Melotti60901872010-12-01 00:56:10 +0000255.. _warning-ignored:
256
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000257Updating Code For New Versions of Python
258----------------------------------------
259
260Warnings that are only of interest to the developer are ignored by default. As
261such you should make sure to test your code with typically ignored warnings
262made visible. You can do this from the command-line by passing :option:`-Wd`
263to the interpreter (this is shorthand for :option:`-W default`). This enables
264default handling for all warnings, including those that are ignored by default.
265To change what action is taken for encountered warnings you simply change what
266argument is passed to :option:`-W`, e.g. :option:`-W error`. See the
267:option:`-W` flag for more details on what is possible.
268
269To programmatically do the same as :option:`-Wd`, use::
270
271 warnings.simplefilter('default')
272
273Make sure to execute this code as soon as possible. This prevents the
274registering of what warnings have been raised from unexpectedly influencing how
275future warnings are treated.
276
277Having certain warnings ignored by default is done to prevent a user from
278seeing warnings that are only of interest to the developer. As you do not
279necessarily have control over what interpreter a user uses to run their code,
280it is possible that a new version of Python will be released between your
281release cycles. The new interpreter release could trigger new warnings in your
282code that were not there in an older interpreter, e.g.
283:exc:`DeprecationWarning` for a module that you are using. While you as a
284developer want to be notified that your code is using a deprecated module, to a
285user this information is essentially noise and provides no benefit to them.
286
Ezio Melotti60901872010-12-01 00:56:10 +0000287The :mod:`unittest` module has been also updated to use the ``'default'``
288filter while running tests.
289
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000290
Georg Brandl116aa622007-08-15 14:28:22 +0000291.. _warning-functions:
292
293Available Functions
294-------------------
295
296
Georg Brandl7f01a132009-09-16 15:58:14 +0000297.. function:: warn(message, category=None, stacklevel=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299 Issue a warning, or maybe ignore it or raise an exception. The *category*
300 argument, if given, must be a warning category class (see above); it defaults to
301 :exc:`UserWarning`. Alternatively *message* can be a :exc:`Warning` instance,
302 in which case *category* will be ignored and ``message.__class__`` will be used.
303 In this case the message text will be ``str(message)``. This function raises an
304 exception if the particular warning issued is changed into an error by the
305 warnings filter see above. The *stacklevel* argument can be used by wrapper
306 functions written in Python, like this::
307
308 def deprecation(message):
309 warnings.warn(message, DeprecationWarning, stacklevel=2)
310
311 This makes the warning refer to :func:`deprecation`'s caller, rather than to the
312 source of :func:`deprecation` itself (since the latter would defeat the purpose
313 of the warning message).
314
315
Georg Brandl7f01a132009-09-16 15:58:14 +0000316.. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000317
318 This is a low-level interface to the functionality of :func:`warn`, passing in
319 explicitly the message, category, filename and line number, and optionally the
320 module name and the registry (which should be the ``__warningregistry__``
321 dictionary of the module). The module name defaults to the filename with
322 ``.py`` stripped; if no registry is passed, the warning is never suppressed.
323 *message* must be a string and *category* a subclass of :exc:`Warning` or
324 *message* may be a :exc:`Warning` instance, in which case *category* will be
325 ignored.
326
327 *module_globals*, if supplied, should be the global namespace in use by the code
328 for which the warning is issued. (This argument is used to support displaying
Christian Heimes3279b5d2007-12-09 15:58:13 +0000329 source for modules found in zipfiles or other non-filesystem import
330 sources).
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332
Georg Brandl7f01a132009-09-16 15:58:14 +0000333.. function:: showwarning(message, category, filename, lineno, file=None, line=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000334
335 Write a warning to a file. The default implementation calls
Christian Heimes33fe8092008-04-13 13:53:33 +0000336 ``formatwarning(message, category, filename, lineno, line)`` and writes the
337 resulting string to *file*, which defaults to ``sys.stderr``. You may replace
338 this function with an alternative implementation by assigning to
Georg Brandl116aa622007-08-15 14:28:22 +0000339 ``warnings.showwarning``.
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000340 *line* is a line of source code to be included in the warning
Georg Brandl48310cd2009-01-03 21:18:54 +0000341 message; if *line* is not supplied, :func:`showwarning` will
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000342 try to read the line specified by *filename* and *lineno*.
Georg Brandl116aa622007-08-15 14:28:22 +0000343
344
Georg Brandl7f01a132009-09-16 15:58:14 +0000345.. function:: formatwarning(message, category, filename, lineno, line=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000346
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000347 Format a warning the standard way. This returns a string which may contain
348 embedded newlines and ends in a newline. *line* is a line of source code to
349 be included in the warning message; if *line* is not supplied,
350 :func:`formatwarning` will try to read the line specified by *filename* and
351 *lineno*.
Georg Brandl116aa622007-08-15 14:28:22 +0000352
353
Georg Brandl7f01a132009-09-16 15:58:14 +0000354.. function:: filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000356 Insert an entry into the list of :ref:`warnings filter specifications
357 <warning-filter>`. The entry is inserted at the front by default; if
358 *append* is true, it is inserted at the end. This checks the types of the
359 arguments, compiles the *message* and *module* regular expressions, and
360 inserts them as a tuple in the list of warnings filters. Entries closer to
Georg Brandl116aa622007-08-15 14:28:22 +0000361 the front of the list override entries later in the list, if both match a
362 particular warning. Omitted arguments default to a value that matches
363 everything.
364
365
Georg Brandl7f01a132009-09-16 15:58:14 +0000366.. function:: simplefilter(action, category=Warning, lineno=0, append=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000367
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000368 Insert a simple entry into the list of :ref:`warnings filter specifications
369 <warning-filter>`. The meaning of the function parameters is as for
370 :func:`filterwarnings`, but regular expressions are not needed as the filter
371 inserted always matches any message in any module as long as the category and
372 line number match.
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374
375.. function:: resetwarnings()
376
377 Reset the warnings filter. This discards the effect of all previous calls to
378 :func:`filterwarnings`, including that of the :option:`-W` command line options
379 and calls to :func:`simplefilter`.
380
Brett Cannonec92e182008-09-02 02:46:59 +0000381
Brett Cannon1cd02472008-09-09 01:52:27 +0000382Available Context Managers
383--------------------------
Brett Cannonec92e182008-09-02 02:46:59 +0000384
Georg Brandl7f01a132009-09-16 15:58:14 +0000385.. class:: catch_warnings(\*, record=False, module=None)
Brett Cannonec92e182008-09-02 02:46:59 +0000386
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000387 A context manager that copies and, upon exit, restores the warnings filter
388 and the :func:`showwarning` function.
389 If the *record* argument is :const:`False` (the default) the context manager
390 returns :class:`None` on entry. If *record* is :const:`True`, a list is
391 returned that is progressively populated with objects as seen by a custom
392 :func:`showwarning` function (which also suppresses output to ``sys.stdout``).
393 Each object in the list has attributes with the same names as the arguments to
394 :func:`showwarning`.
Brett Cannonec92e182008-09-02 02:46:59 +0000395
Brett Cannon1cd02472008-09-09 01:52:27 +0000396 The *module* argument takes a module that will be used instead of the
397 module returned when you import :mod:`warnings` whose filter will be
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000398 protected. This argument exists primarily for testing the :mod:`warnings`
Brett Cannon1cd02472008-09-09 01:52:27 +0000399 module itself.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000400
401 .. note::
402
403 The :class:`catch_warnings` manager works by replacing and
404 then later restoring the module's
405 :func:`showwarning` function and internal list of filter
406 specifications. This means the context manager is modifying
407 global state and therefore is not thread-safe.