blob: 91ab0854b57a94f2b197b5803318d5f0ab6cae84 [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
12Warning messages are typically issued in situations where it is useful to alert
13the user of some condition in a program, where that condition (normally) doesn't
14warrant raising an exception and terminating the program. For example, one
15might want to issue a warning when a program uses an obsolete module.
16
17Python programmers issue warnings by calling the :func:`warn` function defined
Benjamin Peterson092a1f72008-03-31 21:57:13 +000018in this module. (C programmers use :cfunc:`PyErr_WarnEx`; see
Georg Brandl8ec7f652007-08-15 14:28:01 +000019:ref:`exceptionhandling` for details).
20
21Warning messages are normally written to ``sys.stderr``, but their disposition
22can be changed flexibly, from ignoring all warnings to turning them into
23exceptions. 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
25is issued. Repetitions of a particular warning for the same source location are
26typically suppressed.
27
28There are two stages in warning control: first, each time a warning is issued, a
29determination is made whether a message should be issued or not; next, if a
30message is to be issued, it is formatted and printed using a user-settable hook.
31
32The determination whether to issue a warning message is controlled by the
33warning filter, which is a sequence of matching rules and actions. Rules can be
34added to the filter by calling :func:`filterwarnings` and reset to its default
35state by calling :func:`resetwarnings`.
36
37The printing of warning messages is done by calling :func:`showwarning`, which
38may be overridden; the default implementation of this function formats the
39message by calling :func:`formatwarning`, which is also available for use by
40custom implementations.
41
42
43.. _warning-categories:
44
45Warning Categories
46------------------
47
48There are a number of built-in exceptions that represent warning categories.
49This categorization is useful to be able to filter out groups of warnings. The
50following 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 |
Brett Cannon6fdd3dc2010-01-10 02:56:19 +000062| | features (ignored by default). |
Georg Brandl8ec7f652007-08-15 14:28:01 +000063+----------------------------------+-----------------------------------------------+
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
85While these are technically built-in exceptions, they are documented here,
86because conceptually they belong to the warnings mechanism.
87
88User code can define additional warning categories by subclassing one of the
89standard warning categories. A warning category must always be a subclass of
90the :exc:`Warning` class.
91
Brett Cannon6fdd3dc2010-01-10 02:56:19 +000092.. versionchanged:: 2.7
93 :exc:`DeprecationWarning` is ignored by default.
94
Georg Brandl8ec7f652007-08-15 14:28:01 +000095
96.. _warning-filter:
97
98The Warnings Filter
99-------------------
100
101The warnings filter controls whether warnings are ignored, displayed, or turned
102into errors (raising an exception).
103
104Conceptually, the warnings filter maintains an ordered list of filter
105specifications; any specific warning is matched against each filter
106specification in the list in turn until a match is found; the match determines
107the disposition of the match. Each entry is a tuple of the form (*action*,
108*message*, *category*, *module*, *lineno*), where:
109
110* *action* is one of the following strings:
111
112 +---------------+----------------------------------------------+
113 | Value | Disposition |
114 +===============+==============================================+
115 | ``"error"`` | turn matching warnings into exceptions |
116 +---------------+----------------------------------------------+
117 | ``"ignore"`` | never print matching warnings |
118 +---------------+----------------------------------------------+
119 | ``"always"`` | always print matching warnings |
120 +---------------+----------------------------------------------+
121 | ``"default"`` | print the first occurrence of matching |
122 | | warnings for each location where the warning |
123 | | is issued |
124 +---------------+----------------------------------------------+
125 | ``"module"`` | print the first occurrence of matching |
126 | | warnings for each module where the warning |
127 | | is issued |
128 +---------------+----------------------------------------------+
129 | ``"once"`` | print only the first occurrence of matching |
130 | | warnings, regardless of location |
131 +---------------+----------------------------------------------+
132
133* *message* is a string containing a regular expression that the warning message
Georg Brandlf0169702009-09-05 16:47:17 +0000134 must match (the match is compiled to always be case-insensitive).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000135
136* *category* is a class (a subclass of :exc:`Warning`) of which the warning
Georg Brandlf0169702009-09-05 16:47:17 +0000137 category must be a subclass in order to match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000138
139* *module* is a string containing a regular expression that the module name must
Georg Brandlf0169702009-09-05 16:47:17 +0000140 match (the match is compiled to be case-sensitive).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000141
142* *lineno* is an integer that the line number where the warning occurred must
Georg Brandlf0169702009-09-05 16:47:17 +0000143 match, or ``0`` to match all line numbers.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000144
145Since the :exc:`Warning` class is derived from the built-in :exc:`Exception`
146class, to turn a warning into an error we simply raise ``category(message)``.
147
148The warnings filter is initialized by :option:`-W` options passed to the Python
149interpreter command line. The interpreter saves the arguments for all
150:option:`-W` options without interpretation in ``sys.warnoptions``; the
151:mod:`warnings` module parses these when it is first imported (invalid options
152are ignored, after printing a message to ``sys.stderr``).
153
Georg Brandl8ec7f652007-08-15 14:28:01 +0000154
Brett Cannon672237d2008-09-09 00:49:16 +0000155.. _warning-suppress:
156
157Temporarily Suppressing Warnings
158--------------------------------
159
Nick Coghland2e09382008-09-11 12:11:06 +0000160If you are using code that you know will raise a warning, such as a deprecated
161function, but do not want to see the warning, then it is possible to suppress
162the warning using the :class:`catch_warnings` context manager::
Brett Cannon672237d2008-09-09 00:49:16 +0000163
164 import warnings
165
166 def fxn():
167 warnings.warn("deprecated", DeprecationWarning)
168
169 with warnings.catch_warnings():
170 warnings.simplefilter("ignore")
171 fxn()
172
173While within the context manager all warnings will simply be ignored. This
174allows you to use known-deprecated code without having to see the warning while
175not suppressing the warning for other code that might not be aware of its use
176of deprecated code.
177
178
179.. _warning-testing:
180
181Testing Warnings
182----------------
183
184To test warnings raised by code, use the :class:`catch_warnings` context
185manager. With it you can temporarily mutate the warnings filter to facilitate
186your testing. For instance, do the following to capture all raised warnings to
187check::
188
189 import warnings
190
191 def fxn():
192 warnings.warn("deprecated", DeprecationWarning)
193
194 with warnings.catch_warnings(record=True) as w:
195 # Cause all warnings to always be triggered.
196 warnings.simplefilter("always")
197 # Trigger a warning.
198 fxn()
199 # Verify some things
200 assert len(w) == 1
Georg Brandlb4d0ef92009-07-18 09:03:10 +0000201 assert issubclass(w[-1].category, DeprecationWarning)
Brett Cannon672237d2008-09-09 00:49:16 +0000202 assert "deprecated" in str(w[-1].message)
203
204One can also cause all warnings to be exceptions by using ``error`` instead of
205``always``. One thing to be aware of is that if a warning has already been
206raised because of a ``once``/``default`` rule, then no matter what filters are
207set the warning will not be seen again unless the warnings registry related to
208the warning has been cleared.
209
210Once the context manager exits, the warnings filter is restored to its state
211when the context was entered. This prevents tests from changing the warnings
212filter in unexpected ways between tests and leading to indeterminate test
Nick Coghland2e09382008-09-11 12:11:06 +0000213results. The :func:`showwarning` function in the module is also restored to
214its original value.
215
216When testing multiple operations that raise the same kind of warning, it
217is important to test them in a manner that confirms each operation is raising
218a new warning (e.g. set warnings to be raised as exceptions and check the
219operations raise exceptions, check that the length of the warning list
220continues to increase after each operation, or else delete the previous
221entries from the warnings list before each new operation).
Brett Cannon672237d2008-09-09 00:49:16 +0000222
223
Brett Cannon6fdd3dc2010-01-10 02:56:19 +0000224Updating Code For New Versions of Python
225----------------------------------------
226
227Warnings that are only of interest to the developer are ignored by default. As
228such you should make sure to test your code with typically ignored warnings
229made visible. You can do this from the command-line by passing :option:`-Wd`
230to the interpreter (this is shorthand for :option:`-W default`). This enables
231default handling for all warnings, including those that are ignored by default.
232To change what action is taken for encountered warnings you simply change what
233argument is passed to :option:`-W`, e.g. :option:`-W error`. See the
234:option:`-W` flag for more details on what is possible.
235
236To programmatically do the same as :option:`-Wd`, use::
237
238 warnings.simplefilter('default')
239
240Make sure to execute this code as soon as possible. This prevents the
241registering of what warnings have been raised from unexpectedly influencing how
242future warnings are treated.
243
244Having certain warnings ignored by default is done to prevent a user from
245seeing warnings that are only of interest to the developer. As you do not
246necessarily have control over what interpreter a user uses to run their code,
247it is possible that a new version of Python will be released between your
248release cycles. The new interpreter release could trigger new warnings in your
249code that were not there in an older interpreter, e.g.
250:exc:`DeprecationWarning` for a module that you are using. While you as a
251developer want to be notified that your code is using a deprecated module, to a
252user this information is essentially noise and provides no benefit to them.
253
254
Georg Brandl8ec7f652007-08-15 14:28:01 +0000255.. _warning-functions:
256
257Available Functions
258-------------------
259
260
261.. function:: warn(message[, category[, stacklevel]])
262
263 Issue a warning, or maybe ignore it or raise an exception. The *category*
264 argument, if given, must be a warning category class (see above); it defaults to
265 :exc:`UserWarning`. Alternatively *message* can be a :exc:`Warning` instance,
266 in which case *category* will be ignored and ``message.__class__`` will be used.
267 In this case the message text will be ``str(message)``. This function raises an
268 exception if the particular warning issued is changed into an error by the
269 warnings filter see above. The *stacklevel* argument can be used by wrapper
270 functions written in Python, like this::
271
272 def deprecation(message):
273 warnings.warn(message, DeprecationWarning, stacklevel=2)
274
275 This makes the warning refer to :func:`deprecation`'s caller, rather than to the
276 source of :func:`deprecation` itself (since the latter would defeat the purpose
277 of the warning message).
278
279
280.. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]])
281
282 This is a low-level interface to the functionality of :func:`warn`, passing in
283 explicitly the message, category, filename and line number, and optionally the
284 module name and the registry (which should be the ``__warningregistry__``
285 dictionary of the module). The module name defaults to the filename with
286 ``.py`` stripped; if no registry is passed, the warning is never suppressed.
287 *message* must be a string and *category* a subclass of :exc:`Warning` or
288 *message* may be a :exc:`Warning` instance, in which case *category* will be
289 ignored.
290
291 *module_globals*, if supplied, should be the global namespace in use by the code
292 for which the warning is issued. (This argument is used to support displaying
Brett Cannon338d4182007-12-09 05:09:37 +0000293 source for modules found in zipfiles or other non-filesystem import
294 sources).
295
296 .. versionchanged:: 2.5
Georg Brandl4aa8df22008-04-13 07:07:44 +0000297 Added the *module_globals* parameter.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000298
299
Christian Heimes28104c52007-11-27 23:16:44 +0000300.. function:: warnpy3k(message[, category[, stacklevel]])
301
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000302 Issue a warning related to Python 3.x deprecation. Warnings are only shown
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000303 when Python is started with the -3 option. Like :func:`warn` *message* must
Christian Heimes28104c52007-11-27 23:16:44 +0000304 be a string and *category* a subclass of :exc:`Warning`. :func:`warnpy3k`
305 is using :exc:`DeprecationWarning` as default warning class.
306
Benjamin Peterson72f94f72009-07-12 16:56:54 +0000307 .. versionadded:: 2.6
308
Christian Heimes28104c52007-11-27 23:16:44 +0000309
Brett Cannone9746892008-04-12 23:44:07 +0000310.. function:: showwarning(message, category, filename, lineno[, file[, line]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000311
312 Write a warning to a file. The default implementation calls
Brett Cannone9746892008-04-12 23:44:07 +0000313 ``formatwarning(message, category, filename, lineno, line)`` and writes the
314 resulting string to *file*, which defaults to ``sys.stderr``. You may replace
315 this function with an alternative implementation by assigning to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316 ``warnings.showwarning``.
Andrew M. Kuchling311c5802008-05-10 17:37:05 +0000317 *line* is a line of source code to be included in the warning
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000318 message; if *line* is not supplied, :func:`showwarning` will
Andrew M. Kuchling311c5802008-05-10 17:37:05 +0000319 try to read the line specified by *filename* and *lineno*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000320
Brett Cannon6c4cff02009-03-11 04:51:06 +0000321 .. versionchanged:: 2.7
322 The *line* argument is required to be supported.
Brett Cannone9746892008-04-12 23:44:07 +0000323
324
325.. function:: formatwarning(message, category, filename, lineno[, line])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000326
Georg Brandlf0169702009-09-05 16:47:17 +0000327 Format a warning the standard way. This returns a string which may contain
328 embedded newlines and ends in a newline. *line* is a line of source code to
329 be included in the warning message; if *line* is not supplied,
330 :func:`formatwarning` will try to read the line specified by *filename* and
331 *lineno*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000332
Georg Brandl4aa8df22008-04-13 07:07:44 +0000333 .. versionchanged:: 2.6
334 Added the *line* argument.
Brett Cannone9746892008-04-12 23:44:07 +0000335
Georg Brandl8ec7f652007-08-15 14:28:01 +0000336
337.. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]])
338
Georg Brandlf0169702009-09-05 16:47:17 +0000339 Insert an entry into the list of :ref:`warnings filter specifications
340 <warning-filter>`. The entry is inserted at the front by default; if
341 *append* is true, it is inserted at the end. This checks the types of the
342 arguments, compiles the *message* and *module* regular expressions, and
343 inserts them as a tuple in the list of warnings filters. Entries closer to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000344 the front of the list override entries later in the list, if both match a
345 particular warning. Omitted arguments default to a value that matches
346 everything.
347
348
349.. function:: simplefilter(action[, category[, lineno[, append]]])
350
Georg Brandlf0169702009-09-05 16:47:17 +0000351 Insert a simple entry into the list of :ref:`warnings filter specifications
352 <warning-filter>`. The meaning of the function parameters is as for
353 :func:`filterwarnings`, but regular expressions are not needed as the filter
354 inserted always matches any message in any module as long as the category and
355 line number match.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000356
357
358.. function:: resetwarnings()
359
360 Reset the warnings filter. This discards the effect of all previous calls to
361 :func:`filterwarnings`, including that of the :option:`-W` command line options
362 and calls to :func:`simplefilter`.
363
Brett Cannon1eaf0742008-09-02 01:25:16 +0000364
Brett Cannon672237d2008-09-09 00:49:16 +0000365Available Context Managers
366--------------------------
Brett Cannon1eaf0742008-09-02 01:25:16 +0000367
Brett Cannon672237d2008-09-09 00:49:16 +0000368.. class:: catch_warnings([\*, record=False, module=None])
Brett Cannon1eaf0742008-09-02 01:25:16 +0000369
Nick Coghland2e09382008-09-11 12:11:06 +0000370 A context manager that copies and, upon exit, restores the warnings filter
371 and the :func:`showwarning` function.
372 If the *record* argument is :const:`False` (the default) the context manager
373 returns :class:`None` on entry. If *record* is :const:`True`, a list is
374 returned that is progressively populated with objects as seen by a custom
375 :func:`showwarning` function (which also suppresses output to ``sys.stdout``).
376 Each object in the list has attributes with the same names as the arguments to
377 :func:`showwarning`.
Brett Cannon1eaf0742008-09-02 01:25:16 +0000378
Brett Cannon672237d2008-09-09 00:49:16 +0000379 The *module* argument takes a module that will be used instead of the
380 module returned when you import :mod:`warnings` whose filter will be
Nick Coghland2e09382008-09-11 12:11:06 +0000381 protected. This argument exists primarily for testing the :mod:`warnings`
Brett Cannon672237d2008-09-09 00:49:16 +0000382 module itself.
Brett Cannon1eaf0742008-09-02 01:25:16 +0000383
384 .. note::
385
Andrew M. Kuchlingd8862902010-04-02 17:48:23 +0000386 The :class:`catch_warnings` manager works by replacing and
387 then later restoring the module's
388 :func:`showwarning` function and internal list of filter
389 specifications. This means the context manager is modifying
390 global state and therefore is not thread-safe.
391
392 .. note::
393
Brett Cannon1eaf0742008-09-02 01:25:16 +0000394 In Python 3.0, the arguments to the constructor for
395 :class:`catch_warnings` are keyword-only arguments.
396
397 .. versionadded:: 2.6
398