blob: f9d01b25b1f45a3a04e1c57b21381f7e4c144887 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`warnings` --- Warning control
3===================================
4
5.. index:: single: warnings
6
7.. module:: warnings
8 :synopsis: Issue warning messages and control their disposition.
9
10
Georg Brandl116aa622007-08-15 14:28:22 +000011Warning messages are typically issued in situations where it is useful to alert
12the user of some condition in a program, where that condition (normally) doesn't
13warrant raising an exception and terminating the program. For example, one
14might want to issue a warning when a program uses an obsolete module.
15
16Python programmers issue warnings by calling the :func:`warn` function defined
17in this module. (C programmers use :cfunc:`PyErr_WarnEx`; see
18:ref:`exceptionhandling` for details).
19
20Warning messages are normally written to ``sys.stderr``, but their disposition
21can be changed flexibly, from ignoring all warnings to turning them into
22exceptions. The disposition of warnings can vary based on the warning category
23(see below), the text of the warning message, and the source location where it
24is issued. Repetitions of a particular warning for the same source location are
25typically suppressed.
26
27There are two stages in warning control: first, each time a warning is issued, a
28determination is made whether a message should be issued or not; next, if a
29message is to be issued, it is formatted and printed using a user-settable hook.
30
31The determination whether to issue a warning message is controlled by the
32warning filter, which is a sequence of matching rules and actions. Rules can be
33added to the filter by calling :func:`filterwarnings` and reset to its default
34state by calling :func:`resetwarnings`.
35
36The printing of warning messages is done by calling :func:`showwarning`, which
37may be overridden; the default implementation of this function formats the
38message by calling :func:`formatwarning`, which is also available for use by
39custom implementations.
40
41
42.. _warning-categories:
43
44Warning Categories
45------------------
46
47There are a number of built-in exceptions that represent warning categories.
48This categorization is useful to be able to filter out groups of warnings. The
49following warnings category classes are currently defined:
50
51+----------------------------------+-----------------------------------------------+
52| Class | Description |
53+==================================+===============================================+
54| :exc:`Warning` | This is the base class of all warning |
55| | category classes. It is a subclass of |
56| | :exc:`Exception`. |
57+----------------------------------+-----------------------------------------------+
58| :exc:`UserWarning` | The default category for :func:`warn`. |
59+----------------------------------+-----------------------------------------------+
60| :exc:`DeprecationWarning` | Base category for warnings about deprecated |
61| | features. |
62+----------------------------------+-----------------------------------------------+
63| :exc:`SyntaxWarning` | Base category for warnings about dubious |
64| | syntactic features. |
65+----------------------------------+-----------------------------------------------+
66| :exc:`RuntimeWarning` | Base category for warnings about dubious |
67| | runtime features. |
68+----------------------------------+-----------------------------------------------+
69| :exc:`FutureWarning` | Base category for warnings about constructs |
70| | that will change semantically in the future. |
71+----------------------------------+-----------------------------------------------+
72| :exc:`PendingDeprecationWarning` | Base category for warnings about features |
73| | that will be deprecated in the future |
74| | (ignored by default). |
75+----------------------------------+-----------------------------------------------+
76| :exc:`ImportWarning` | Base category for warnings triggered during |
77| | the process of importing a module (ignored by |
78| | default). |
79+----------------------------------+-----------------------------------------------+
80| :exc:`UnicodeWarning` | Base category for warnings related to |
81| | Unicode. |
82+----------------------------------+-----------------------------------------------+
Guido van Rossum98297ee2007-11-06 21:34:58 +000083| :exc:`BytesWarning` | Base category for warnings related to |
84| | :class:`bytes` and :class:`buffer`. |
85+----------------------------------+-----------------------------------------------+
86
Georg Brandl116aa622007-08-15 14:28:22 +000087
88While these are technically built-in exceptions, they are documented here,
89because conceptually they belong to the warnings mechanism.
90
91User code can define additional warning categories by subclassing one of the
92standard warning categories. A warning category must always be a subclass of
93the :exc:`Warning` class.
94
95
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
134 must match (the match is compiled to always be case-insensitive)
135
136* *category* is a class (a subclass of :exc:`Warning`) of which the warning
137 category must be a subclass in order to match
138
139* *module* is a string containing a regular expression that the module name must
140 match (the match is compiled to be case-sensitive)
141
142* *lineno* is an integer that the line number where the warning occurred must
143 match, or ``0`` to match all line numbers
144
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
154The warnings that are ignored by default may be enabled by passing :option:`-Wd`
155to the interpreter. This enables default handling for all warnings, including
156those that are normally ignored by default. This is particular useful for
157enabling ImportWarning when debugging problems importing a developed package.
158ImportWarning can also be enabled explicitly in Python code using::
159
160 warnings.simplefilter('default', ImportWarning)
161
162
Brett Cannon1cd02472008-09-09 01:52:27 +0000163.. _warning-suppress:
164
165Temporarily Suppressing Warnings
166--------------------------------
167
168If you are using code that you know will raise a warning, such some deprecated
169function, but do not want to see the warning, then suppress the warning using
170the :class:`catch_warnings` context manager::
171
172 import warnings
173
174 def fxn():
175 warnings.warn("deprecated", DeprecationWarning)
176
177 with warnings.catch_warnings():
178 warnings.simplefilter("ignore")
179 fxn()
180
181While within the context manager all warnings will simply be ignored. This
182allows you to use known-deprecated code without having to see the warning while
183not suppressing the warning for other code that might not be aware of its use
184of deprecated code.
185
186
187.. _warning-testing:
188
189Testing Warnings
190----------------
191
192To test warnings raised by code, use the :class:`catch_warnings` context
193manager. With it you can temporarily mutate the warnings filter to facilitate
194your testing. For instance, do the following to capture all raised warnings to
195check::
196
197 import warnings
198
199 def fxn():
200 warnings.warn("deprecated", DeprecationWarning)
201
202 with warnings.catch_warnings(record=True) as w:
203 # Cause all warnings to always be triggered.
204 warnings.simplefilter("always")
205 # Trigger a warning.
206 fxn()
207 # Verify some things
208 assert len(w) == 1
209 assert isinstance(w[-1].category, DeprecationWarning)
210 assert "deprecated" in str(w[-1].message)
211
212One can also cause all warnings to be exceptions by using ``error`` instead of
213``always``. One thing to be aware of is that if a warning has already been
214raised because of a ``once``/``default`` rule, then no matter what filters are
215set the warning will not be seen again unless the warnings registry related to
216the warning has been cleared.
217
218Once the context manager exits, the warnings filter is restored to its state
219when the context was entered. This prevents tests from changing the warnings
220filter in unexpected ways between tests and leading to indeterminate test
221results.
222
223
Georg Brandl116aa622007-08-15 14:28:22 +0000224.. _warning-functions:
225
226Available Functions
227-------------------
228
229
230.. function:: warn(message[, category[, stacklevel]])
231
232 Issue a warning, or maybe ignore it or raise an exception. The *category*
233 argument, if given, must be a warning category class (see above); it defaults to
234 :exc:`UserWarning`. Alternatively *message* can be a :exc:`Warning` instance,
235 in which case *category* will be ignored and ``message.__class__`` will be used.
236 In this case the message text will be ``str(message)``. This function raises an
237 exception if the particular warning issued is changed into an error by the
238 warnings filter see above. The *stacklevel* argument can be used by wrapper
239 functions written in Python, like this::
240
241 def deprecation(message):
242 warnings.warn(message, DeprecationWarning, stacklevel=2)
243
244 This makes the warning refer to :func:`deprecation`'s caller, rather than to the
245 source of :func:`deprecation` itself (since the latter would defeat the purpose
246 of the warning message).
247
248
249.. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]])
250
251 This is a low-level interface to the functionality of :func:`warn`, passing in
252 explicitly the message, category, filename and line number, and optionally the
253 module name and the registry (which should be the ``__warningregistry__``
254 dictionary of the module). The module name defaults to the filename with
255 ``.py`` stripped; if no registry is passed, the warning is never suppressed.
256 *message* must be a string and *category* a subclass of :exc:`Warning` or
257 *message* may be a :exc:`Warning` instance, in which case *category* will be
258 ignored.
259
260 *module_globals*, if supplied, should be the global namespace in use by the code
261 for which the warning is issued. (This argument is used to support displaying
Christian Heimes3279b5d2007-12-09 15:58:13 +0000262 source for modules found in zipfiles or other non-filesystem import
263 sources).
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265
Christian Heimes33fe8092008-04-13 13:53:33 +0000266.. function:: showwarning(message, category, filename, lineno[, file[, line]])
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268 Write a warning to a file. The default implementation calls
Christian Heimes33fe8092008-04-13 13:53:33 +0000269 ``formatwarning(message, category, filename, lineno, line)`` and writes the
270 resulting string to *file*, which defaults to ``sys.stderr``. You may replace
271 this function with an alternative implementation by assigning to
Georg Brandl116aa622007-08-15 14:28:22 +0000272 ``warnings.showwarning``.
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000273 *line* is a line of source code to be included in the warning
274 message; if *line* is not supplied, :func:`showwarning` will
275 try to read the line specified by *filename* and *lineno*.
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277
Christian Heimes33fe8092008-04-13 13:53:33 +0000278.. function:: formatwarning(message, category, filename, lineno[, line])
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280 Format a warning the standard way. This returns a string which may contain
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000281 embedded newlines and ends in a newline. *line* is
282 a line of source code to be included in the warning message; if *line* is not supplied,
283 :func:`formatwarning` will try to read the line specified by *filename* and *lineno*.
Georg Brandl116aa622007-08-15 14:28:22 +0000284
285
286.. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]])
287
288 Insert an entry into the list of warnings filters. The entry is inserted at the
289 front by default; if *append* is true, it is inserted at the end. This checks
290 the types of the arguments, compiles the message and module regular expressions,
291 and inserts them as a tuple in the list of warnings filters. Entries closer to
292 the front of the list override entries later in the list, if both match a
293 particular warning. Omitted arguments default to a value that matches
294 everything.
295
296
297.. function:: simplefilter(action[, category[, lineno[, append]]])
298
299 Insert a simple entry into the list of warnings filters. The meaning of the
300 function parameters is as for :func:`filterwarnings`, but regular expressions
301 are not needed as the filter inserted always matches any message in any module
302 as long as the category and line number match.
303
304
305.. function:: resetwarnings()
306
307 Reset the warnings filter. This discards the effect of all previous calls to
308 :func:`filterwarnings`, including that of the :option:`-W` command line options
309 and calls to :func:`simplefilter`.
310
Brett Cannonec92e182008-09-02 02:46:59 +0000311
Brett Cannon1cd02472008-09-09 01:52:27 +0000312Available Context Managers
313--------------------------
Brett Cannonec92e182008-09-02 02:46:59 +0000314
315.. class:: catch_warnings([\*, record=False, module=None])
316
Brett Cannon1cd02472008-09-09 01:52:27 +0000317 A context manager that copies and, upon exit, restores the warnings filter.
318 If the *record* argument is False (the default) the context manager returns
319 :class:`None`. If *record* is true, a list is returned that is populated
320 with objects as seen by a custom :func:`showwarning` function (which also
321 suppresses output to ``sys.stdout``). Each object has attributes with the
322 same names as the arguments to :func:`showwarning`.
Brett Cannonec92e182008-09-02 02:46:59 +0000323
Brett Cannon1cd02472008-09-09 01:52:27 +0000324 The *module* argument takes a module that will be used instead of the
325 module returned when you import :mod:`warnings` whose filter will be
326 protected. This arguments exists primarily for testing the :mod:`warnings`
327 module itself.
Brett Cannonec92e182008-09-02 02:46:59 +0000328
329 .. versionadded:: 2.6
330
331 .. versionchanged:: 3.0
332
333 Constructor arguments turned into keyword-only arguments.
334