blob: e62be551bb57560a097a7ca0ca25618214e9cffa [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
9
Georg Brandl116aa622007-08-15 14:28:22 +000010Warning messages are typically issued in situations where it is useful to alert
11the user of some condition in a program, where that condition (normally) doesn't
12warrant raising an exception and terminating the program. For example, one
13might want to issue a warning when a program uses an obsolete module.
14
15Python programmers issue warnings by calling the :func:`warn` function defined
16in this module. (C programmers use :cfunc:`PyErr_WarnEx`; see
17:ref:`exceptionhandling` for details).
18
19Warning messages are normally written to ``sys.stderr``, but their disposition
20can be changed flexibly, from ignoring all warnings to turning them into
21exceptions. The disposition of warnings can vary based on the warning category
22(see below), the text of the warning message, and the source location where it
23is issued. Repetitions of a particular warning for the same source location are
24typically suppressed.
25
26There are two stages in warning control: first, each time a warning is issued, a
27determination is made whether a message should be issued or not; next, if a
28message is to be issued, it is formatted and printed using a user-settable hook.
29
30The determination whether to issue a warning message is controlled by the
31warning filter, which is a sequence of matching rules and actions. Rules can be
32added to the filter by calling :func:`filterwarnings` and reset to its default
33state by calling :func:`resetwarnings`.
34
35The printing of warning messages is done by calling :func:`showwarning`, which
36may be overridden; the default implementation of this function formats the
37message by calling :func:`formatwarning`, which is also available for use by
38custom implementations.
39
40
41.. _warning-categories:
42
43Warning Categories
44------------------
45
46There are a number of built-in exceptions that represent warning categories.
47This categorization is useful to be able to filter out groups of warnings. The
48following warnings category classes are currently defined:
49
50+----------------------------------+-----------------------------------------------+
51| Class | Description |
52+==================================+===============================================+
53| :exc:`Warning` | This is the base class of all warning |
54| | category classes. It is a subclass of |
55| | :exc:`Exception`. |
56+----------------------------------+-----------------------------------------------+
57| :exc:`UserWarning` | The default category for :func:`warn`. |
58+----------------------------------+-----------------------------------------------+
59| :exc:`DeprecationWarning` | Base category for warnings about deprecated |
60| | features. |
61+----------------------------------+-----------------------------------------------+
62| :exc:`SyntaxWarning` | Base category for warnings about dubious |
63| | syntactic features. |
64+----------------------------------+-----------------------------------------------+
65| :exc:`RuntimeWarning` | Base category for warnings about dubious |
66| | runtime features. |
67+----------------------------------+-----------------------------------------------+
68| :exc:`FutureWarning` | Base category for warnings about constructs |
69| | that will change semantically in the future. |
70+----------------------------------+-----------------------------------------------+
71| :exc:`PendingDeprecationWarning` | Base category for warnings about features |
72| | that will be deprecated in the future |
73| | (ignored by default). |
74+----------------------------------+-----------------------------------------------+
75| :exc:`ImportWarning` | Base category for warnings triggered during |
76| | the process of importing a module (ignored by |
77| | default). |
78+----------------------------------+-----------------------------------------------+
79| :exc:`UnicodeWarning` | Base category for warnings related to |
80| | Unicode. |
81+----------------------------------+-----------------------------------------------+
Guido van Rossum98297ee2007-11-06 21:34:58 +000082| :exc:`BytesWarning` | Base category for warnings related to |
83| | :class:`bytes` and :class:`buffer`. |
84+----------------------------------+-----------------------------------------------+
85
Georg Brandl116aa622007-08-15 14:28:22 +000086
87While these are technically built-in exceptions, they are documented here,
88because conceptually they belong to the warnings mechanism.
89
90User code can define additional warning categories by subclassing one of the
91standard warning categories. A warning category must always be a subclass of
92the :exc:`Warning` class.
93
94
95.. _warning-filter:
96
97The Warnings Filter
98-------------------
99
100The warnings filter controls whether warnings are ignored, displayed, or turned
101into errors (raising an exception).
102
103Conceptually, the warnings filter maintains an ordered list of filter
104specifications; any specific warning is matched against each filter
105specification in the list in turn until a match is found; the match determines
106the disposition of the match. Each entry is a tuple of the form (*action*,
107*message*, *category*, *module*, *lineno*), where:
108
109* *action* is one of the following strings:
110
111 +---------------+----------------------------------------------+
112 | Value | Disposition |
113 +===============+==============================================+
114 | ``"error"`` | turn matching warnings into exceptions |
115 +---------------+----------------------------------------------+
116 | ``"ignore"`` | never print matching warnings |
117 +---------------+----------------------------------------------+
118 | ``"always"`` | always print matching warnings |
119 +---------------+----------------------------------------------+
120 | ``"default"`` | print the first occurrence of matching |
121 | | warnings for each location where the warning |
122 | | is issued |
123 +---------------+----------------------------------------------+
124 | ``"module"`` | print the first occurrence of matching |
125 | | warnings for each module where the warning |
126 | | is issued |
127 +---------------+----------------------------------------------+
128 | ``"once"`` | print only the first occurrence of matching |
129 | | warnings, regardless of location |
130 +---------------+----------------------------------------------+
131
132* *message* is a string containing a regular expression that the warning message
Benjamin Petersona8332062009-09-11 22:36:27 +0000133 must match (the match is compiled to always be case-insensitive).
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135* *category* is a class (a subclass of :exc:`Warning`) of which the warning
Benjamin Petersona8332062009-09-11 22:36:27 +0000136 category must be a subclass in order to match.
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138* *module* is a string containing a regular expression that the module name must
Benjamin Petersona8332062009-09-11 22:36:27 +0000139 match (the match is compiled to be case-sensitive).
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141* *lineno* is an integer that the line number where the warning occurred must
Benjamin Petersona8332062009-09-11 22:36:27 +0000142 match, or ``0`` to match all line numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000143
144Since the :exc:`Warning` class is derived from the built-in :exc:`Exception`
145class, to turn a warning into an error we simply raise ``category(message)``.
146
147The warnings filter is initialized by :option:`-W` options passed to the Python
148interpreter command line. The interpreter saves the arguments for all
149:option:`-W` options without interpretation in ``sys.warnoptions``; the
150:mod:`warnings` module parses these when it is first imported (invalid options
151are ignored, after printing a message to ``sys.stderr``).
152
153The warnings that are ignored by default may be enabled by passing :option:`-Wd`
154to the interpreter. This enables default handling for all warnings, including
155those that are normally ignored by default. This is particular useful for
156enabling ImportWarning when debugging problems importing a developed package.
157ImportWarning can also be enabled explicitly in Python code using::
158
159 warnings.simplefilter('default', ImportWarning)
160
161
Georg Brandlf55aa802010-11-26 08:59:40 +0000162Default Warning Filters
163~~~~~~~~~~~~~~~~~~~~~~~
164
165By default, Python installs several warning filters, which can be overridden by
166the command-line options passed to :option:`-W` and calls to
167:func:`filterwarnings`.
168
169* :exc:`PendingDeprecationWarning`, and :exc:`ImportWarning` are ignored.
170
171* :exc:`BytesWarning` is ignored unless the :option:`-b` option is given once or
172 twice; in this case this warning is either printed (``-b``) or turned into an
173 exception (``-bb``).
174
175
Brett Cannon1cd02472008-09-09 01:52:27 +0000176.. _warning-suppress:
177
178Temporarily Suppressing Warnings
179--------------------------------
180
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000181If you are using code that you know will raise a warning, such as a deprecated
182function, but do not want to see the warning, then it is possible to suppress
183the warning using the :class:`catch_warnings` context manager::
Brett Cannon1cd02472008-09-09 01:52:27 +0000184
185 import warnings
186
187 def fxn():
188 warnings.warn("deprecated", DeprecationWarning)
189
190 with warnings.catch_warnings():
191 warnings.simplefilter("ignore")
192 fxn()
193
194While within the context manager all warnings will simply be ignored. This
195allows you to use known-deprecated code without having to see the warning while
196not suppressing the warning for other code that might not be aware of its use
197of deprecated code.
198
199
200.. _warning-testing:
201
202Testing Warnings
203----------------
204
205To test warnings raised by code, use the :class:`catch_warnings` context
206manager. With it you can temporarily mutate the warnings filter to facilitate
207your testing. For instance, do the following to capture all raised warnings to
208check::
209
210 import warnings
211
212 def fxn():
213 warnings.warn("deprecated", DeprecationWarning)
214
215 with warnings.catch_warnings(record=True) as w:
216 # Cause all warnings to always be triggered.
217 warnings.simplefilter("always")
218 # Trigger a warning.
219 fxn()
220 # Verify some things
221 assert len(w) == 1
Georg Brandlc5605df2009-08-13 08:26:44 +0000222 assert issubclass(w[-1].category, DeprecationWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000223 assert "deprecated" in str(w[-1].message)
224
225One can also cause all warnings to be exceptions by using ``error`` instead of
226``always``. One thing to be aware of is that if a warning has already been
227raised because of a ``once``/``default`` rule, then no matter what filters are
228set the warning will not be seen again unless the warnings registry related to
229the warning has been cleared.
230
231Once the context manager exits, the warnings filter is restored to its state
232when the context was entered. This prevents tests from changing the warnings
233filter in unexpected ways between tests and leading to indeterminate test
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000234results. The :func:`showwarning` function in the module is also restored to
235its original value.
236
237When testing multiple operations that raise the same kind of warning, it
238is important to test them in a manner that confirms each operation is raising
239a new warning (e.g. set warnings to be raised as exceptions and check the
240operations raise exceptions, check that the length of the warning list
241continues to increase after each operation, or else delete the previous
242entries from the warnings list before each new operation).
Brett Cannon1cd02472008-09-09 01:52:27 +0000243
244
Georg Brandl116aa622007-08-15 14:28:22 +0000245.. _warning-functions:
246
247Available Functions
248-------------------
249
250
Georg Brandlb044b2a2009-09-16 16:05:59 +0000251.. function:: warn(message, category=None, stacklevel=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000252
253 Issue a warning, or maybe ignore it or raise an exception. The *category*
254 argument, if given, must be a warning category class (see above); it defaults to
255 :exc:`UserWarning`. Alternatively *message* can be a :exc:`Warning` instance,
256 in which case *category* will be ignored and ``message.__class__`` will be used.
257 In this case the message text will be ``str(message)``. This function raises an
258 exception if the particular warning issued is changed into an error by the
259 warnings filter see above. The *stacklevel* argument can be used by wrapper
260 functions written in Python, like this::
261
262 def deprecation(message):
263 warnings.warn(message, DeprecationWarning, stacklevel=2)
264
265 This makes the warning refer to :func:`deprecation`'s caller, rather than to the
266 source of :func:`deprecation` itself (since the latter would defeat the purpose
267 of the warning message).
268
269
Georg Brandlb044b2a2009-09-16 16:05:59 +0000270.. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272 This is a low-level interface to the functionality of :func:`warn`, passing in
273 explicitly the message, category, filename and line number, and optionally the
274 module name and the registry (which should be the ``__warningregistry__``
275 dictionary of the module). The module name defaults to the filename with
276 ``.py`` stripped; if no registry is passed, the warning is never suppressed.
277 *message* must be a string and *category* a subclass of :exc:`Warning` or
278 *message* may be a :exc:`Warning` instance, in which case *category* will be
279 ignored.
280
281 *module_globals*, if supplied, should be the global namespace in use by the code
282 for which the warning is issued. (This argument is used to support displaying
Christian Heimes3279b5d2007-12-09 15:58:13 +0000283 source for modules found in zipfiles or other non-filesystem import
284 sources).
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286
Georg Brandlb044b2a2009-09-16 16:05:59 +0000287.. function:: showwarning(message, category, filename, lineno, file=None, line=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000288
289 Write a warning to a file. The default implementation calls
Christian Heimes33fe8092008-04-13 13:53:33 +0000290 ``formatwarning(message, category, filename, lineno, line)`` and writes the
291 resulting string to *file*, which defaults to ``sys.stderr``. You may replace
292 this function with an alternative implementation by assigning to
Georg Brandl116aa622007-08-15 14:28:22 +0000293 ``warnings.showwarning``.
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000294 *line* is a line of source code to be included in the warning
Georg Brandl48310cd2009-01-03 21:18:54 +0000295 message; if *line* is not supplied, :func:`showwarning` will
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000296 try to read the line specified by *filename* and *lineno*.
Georg Brandl116aa622007-08-15 14:28:22 +0000297
298
Georg Brandlb044b2a2009-09-16 16:05:59 +0000299.. function:: formatwarning(message, category, filename, lineno, line=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Benjamin Petersona8332062009-09-11 22:36:27 +0000301 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 Brandl116aa622007-08-15 14:28:22 +0000306
307
Georg Brandlb044b2a2009-09-16 16:05:59 +0000308.. function:: filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000309
Benjamin Petersona8332062009-09-11 22:36:27 +0000310 Insert an entry into the list of :ref:`warnings filter specifications
311 <warning-filter>`. The entry is inserted at the front by default; if
312 *append* is true, it is inserted at the end. This checks the types of the
313 arguments, compiles the *message* and *module* regular expressions, and
314 inserts them as a tuple in the list of warnings filters. Entries closer to
Georg Brandl116aa622007-08-15 14:28:22 +0000315 the front of the list override entries later in the list, if both match a
316 particular warning. Omitted arguments default to a value that matches
317 everything.
318
319
Georg Brandlb044b2a2009-09-16 16:05:59 +0000320.. function:: simplefilter(action, category=Warning, lineno=0, append=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000321
Benjamin Petersona8332062009-09-11 22:36:27 +0000322 Insert a simple entry into the list of :ref:`warnings filter specifications
323 <warning-filter>`. The meaning of the function parameters is as for
324 :func:`filterwarnings`, but regular expressions are not needed as the filter
325 inserted always matches any message in any module as long as the category and
326 line number match.
Georg Brandl116aa622007-08-15 14:28:22 +0000327
328
329.. function:: resetwarnings()
330
331 Reset the warnings filter. This discards the effect of all previous calls to
332 :func:`filterwarnings`, including that of the :option:`-W` command line options
333 and calls to :func:`simplefilter`.
334
Brett Cannonec92e182008-09-02 02:46:59 +0000335
Brett Cannon1cd02472008-09-09 01:52:27 +0000336Available Context Managers
337--------------------------
Brett Cannonec92e182008-09-02 02:46:59 +0000338
Georg Brandlb044b2a2009-09-16 16:05:59 +0000339.. class:: catch_warnings(\*, record=False, module=None)
Brett Cannonec92e182008-09-02 02:46:59 +0000340
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000341 A context manager that copies and, upon exit, restores the warnings filter
342 and the :func:`showwarning` function.
343 If the *record* argument is :const:`False` (the default) the context manager
344 returns :class:`None` on entry. If *record* is :const:`True`, a list is
345 returned that is progressively populated with objects as seen by a custom
346 :func:`showwarning` function (which also suppresses output to ``sys.stdout``).
347 Each object in the list has attributes with the same names as the arguments to
348 :func:`showwarning`.
Brett Cannonec92e182008-09-02 02:46:59 +0000349
Brett Cannon1cd02472008-09-09 01:52:27 +0000350 The *module* argument takes a module that will be used instead of the
351 module returned when you import :mod:`warnings` whose filter will be
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000352 protected. This argument exists primarily for testing the :mod:`warnings`
Brett Cannon1cd02472008-09-09 01:52:27 +0000353 module itself.