Debian Codegraph @

cpython27/Doc/library/warnings.rst

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