blob: d36955f6376ab30b3258ada26f3a4cc3356f0d6c [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
11.. versionadded:: 2.1
12
13Warning 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
Benjamin Peterson092a1f72008-03-31 21:57:13 +000019in this module. (C programmers use :cfunc:`PyErr_WarnEx`; see
Georg Brandl8ec7f652007-08-15 14:28:01 +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 |
63| | features. |
64+----------------------------------+-----------------------------------------------+
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+----------------------------------+-----------------------------------------------+
85
86While these are technically built-in exceptions, they are documented here,
87because conceptually they belong to the warnings mechanism.
88
89User code can define additional warning categories by subclassing one of the
90standard warning categories. A warning category must always be a subclass of
91the :exc:`Warning` class.
92
93
94.. _warning-filter:
95
96The Warnings Filter
97-------------------
98
99The warnings filter controls whether warnings are ignored, displayed, or turned
100into errors (raising an exception).
101
102Conceptually, the warnings filter maintains an ordered list of filter
103specifications; any specific warning is matched against each filter
104specification in the list in turn until a match is found; the match determines
105the disposition of the match. Each entry is a tuple of the form (*action*,
106*message*, *category*, *module*, *lineno*), where:
107
108* *action* is one of the following strings:
109
110 +---------------+----------------------------------------------+
111 | Value | Disposition |
112 +===============+==============================================+
113 | ``"error"`` | turn matching warnings into exceptions |
114 +---------------+----------------------------------------------+
115 | ``"ignore"`` | never print matching warnings |
116 +---------------+----------------------------------------------+
117 | ``"always"`` | always print matching warnings |
118 +---------------+----------------------------------------------+
119 | ``"default"`` | print the first occurrence of matching |
120 | | warnings for each location where the warning |
121 | | is issued |
122 +---------------+----------------------------------------------+
123 | ``"module"`` | print the first occurrence of matching |
124 | | warnings for each module where the warning |
125 | | is issued |
126 +---------------+----------------------------------------------+
127 | ``"once"`` | print only the first occurrence of matching |
128 | | warnings, regardless of location |
129 +---------------+----------------------------------------------+
130
131* *message* is a string containing a regular expression that the warning message
132 must match (the match is compiled to always be case-insensitive)
133
134* *category* is a class (a subclass of :exc:`Warning`) of which the warning
135 category must be a subclass in order to match
136
137* *module* is a string containing a regular expression that the module name must
138 match (the match is compiled to be case-sensitive)
139
140* *lineno* is an integer that the line number where the warning occurred must
141 match, or ``0`` to match all line numbers
142
143Since the :exc:`Warning` class is derived from the built-in :exc:`Exception`
144class, to turn a warning into an error we simply raise ``category(message)``.
145
146The warnings filter is initialized by :option:`-W` options passed to the Python
147interpreter command line. The interpreter saves the arguments for all
148:option:`-W` options without interpretation in ``sys.warnoptions``; the
149:mod:`warnings` module parses these when it is first imported (invalid options
150are ignored, after printing a message to ``sys.stderr``).
151
152The warnings that are ignored by default may be enabled by passing :option:`-Wd`
153to the interpreter. This enables default handling for all warnings, including
154those that are normally ignored by default. This is particular useful for
155enabling ImportWarning when debugging problems importing a developed package.
156ImportWarning can also be enabled explicitly in Python code using::
157
158 warnings.simplefilter('default', ImportWarning)
159
160
Brett Cannon672237d2008-09-09 00:49:16 +0000161.. _warning-suppress:
162
163Temporarily Suppressing Warnings
164--------------------------------
165
Nick Coghland2e09382008-09-11 12:11:06 +0000166If you are using code that you know will raise a warning, such as a deprecated
167function, but do not want to see the warning, then it is possible to suppress
168the warning using the :class:`catch_warnings` context manager::
Brett Cannon672237d2008-09-09 00:49:16 +0000169
170 import warnings
171
172 def fxn():
173 warnings.warn("deprecated", DeprecationWarning)
174
175 with warnings.catch_warnings():
176 warnings.simplefilter("ignore")
177 fxn()
178
179While within the context manager all warnings will simply be ignored. This
180allows you to use known-deprecated code without having to see the warning while
181not suppressing the warning for other code that might not be aware of its use
182of deprecated code.
183
184
185.. _warning-testing:
186
187Testing Warnings
188----------------
189
190To test warnings raised by code, use the :class:`catch_warnings` context
191manager. With it you can temporarily mutate the warnings filter to facilitate
192your testing. For instance, do the following to capture all raised warnings to
193check::
194
195 import warnings
196
197 def fxn():
198 warnings.warn("deprecated", DeprecationWarning)
199
200 with warnings.catch_warnings(record=True) as w:
201 # Cause all warnings to always be triggered.
202 warnings.simplefilter("always")
203 # Trigger a warning.
204 fxn()
205 # Verify some things
206 assert len(w) == 1
207 assert isinstance(w[-1].category, DeprecationWarning)
208 assert "deprecated" in str(w[-1].message)
209
210One can also cause all warnings to be exceptions by using ``error`` instead of
211``always``. One thing to be aware of is that if a warning has already been
212raised because of a ``once``/``default`` rule, then no matter what filters are
213set the warning will not be seen again unless the warnings registry related to
214the warning has been cleared.
215
216Once the context manager exits, the warnings filter is restored to its state
217when the context was entered. This prevents tests from changing the warnings
218filter in unexpected ways between tests and leading to indeterminate test
Nick Coghland2e09382008-09-11 12:11:06 +0000219results. The :func:`showwarning` function in the module is also restored to
220its original value.
221
222When testing multiple operations that raise the same kind of warning, it
223is important to test them in a manner that confirms each operation is raising
224a new warning (e.g. set warnings to be raised as exceptions and check the
225operations raise exceptions, check that the length of the warning list
226continues to increase after each operation, or else delete the previous
227entries from the warnings list before each new operation).
Brett Cannon672237d2008-09-09 00:49:16 +0000228
229
Georg Brandl8ec7f652007-08-15 14:28:01 +0000230.. _warning-functions:
231
232Available Functions
233-------------------
234
235
236.. function:: warn(message[, category[, stacklevel]])
237
238 Issue a warning, or maybe ignore it or raise an exception. The *category*
239 argument, if given, must be a warning category class (see above); it defaults to
240 :exc:`UserWarning`. Alternatively *message* can be a :exc:`Warning` instance,
241 in which case *category* will be ignored and ``message.__class__`` will be used.
242 In this case the message text will be ``str(message)``. This function raises an
243 exception if the particular warning issued is changed into an error by the
244 warnings filter see above. The *stacklevel* argument can be used by wrapper
245 functions written in Python, like this::
246
247 def deprecation(message):
248 warnings.warn(message, DeprecationWarning, stacklevel=2)
249
250 This makes the warning refer to :func:`deprecation`'s caller, rather than to the
251 source of :func:`deprecation` itself (since the latter would defeat the purpose
252 of the warning message).
253
254
255.. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]])
256
257 This is a low-level interface to the functionality of :func:`warn`, passing in
258 explicitly the message, category, filename and line number, and optionally the
259 module name and the registry (which should be the ``__warningregistry__``
260 dictionary of the module). The module name defaults to the filename with
261 ``.py`` stripped; if no registry is passed, the warning is never suppressed.
262 *message* must be a string and *category* a subclass of :exc:`Warning` or
263 *message* may be a :exc:`Warning` instance, in which case *category* will be
264 ignored.
265
266 *module_globals*, if supplied, should be the global namespace in use by the code
267 for which the warning is issued. (This argument is used to support displaying
Brett Cannon338d4182007-12-09 05:09:37 +0000268 source for modules found in zipfiles or other non-filesystem import
269 sources).
270
271 .. versionchanged:: 2.5
Georg Brandl4aa8df22008-04-13 07:07:44 +0000272 Added the *module_globals* parameter.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000273
274
Christian Heimes28104c52007-11-27 23:16:44 +0000275.. function:: warnpy3k(message[, category[, stacklevel]])
276
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000277 Issue a warning related to Python 3.x deprecation. Warnings are only shown
Georg Brandl2b92f6b2007-12-06 01:52:24 +0000278 when Python is started with the -3 option. Like :func:`warn` *message* must
Christian Heimes28104c52007-11-27 23:16:44 +0000279 be a string and *category* a subclass of :exc:`Warning`. :func:`warnpy3k`
280 is using :exc:`DeprecationWarning` as default warning class.
281
Benjamin Peterson72f94f72009-07-12 16:56:54 +0000282 .. versionadded:: 2.6
283
Christian Heimes28104c52007-11-27 23:16:44 +0000284
Brett Cannone9746892008-04-12 23:44:07 +0000285.. function:: showwarning(message, category, filename, lineno[, file[, line]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000286
287 Write a warning to a file. The default implementation calls
Brett Cannone9746892008-04-12 23:44:07 +0000288 ``formatwarning(message, category, filename, lineno, line)`` and writes the
289 resulting string to *file*, which defaults to ``sys.stderr``. You may replace
290 this function with an alternative implementation by assigning to
Georg Brandl8ec7f652007-08-15 14:28:01 +0000291 ``warnings.showwarning``.
Andrew M. Kuchling311c5802008-05-10 17:37:05 +0000292 *line* is a line of source code to be included in the warning
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000293 message; if *line* is not supplied, :func:`showwarning` will
Andrew M. Kuchling311c5802008-05-10 17:37:05 +0000294 try to read the line specified by *filename* and *lineno*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000295
Brett Cannon6c4cff02009-03-11 04:51:06 +0000296 .. versionchanged:: 2.7
297 The *line* argument is required to be supported.
Brett Cannone9746892008-04-12 23:44:07 +0000298
299
300.. function:: formatwarning(message, category, filename, lineno[, line])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000301
302 Format a warning the standard way. This returns a string which may contain
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000303 embedded newlines and ends in a newline. *line* is
304 a line of source code to be included in the warning message; if *line* is not supplied,
Andrew M. Kuchling311c5802008-05-10 17:37:05 +0000305 :func:`formatwarning` will try to read the line specified by *filename* and *lineno*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000306
Georg Brandl4aa8df22008-04-13 07:07:44 +0000307 .. versionchanged:: 2.6
308 Added the *line* argument.
Brett Cannone9746892008-04-12 23:44:07 +0000309
Georg Brandl8ec7f652007-08-15 14:28:01 +0000310
311.. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]])
312
313 Insert an entry into the list of warnings filters. The entry is inserted at the
314 front by default; if *append* is true, it is inserted at the end. This checks
315 the types of the arguments, compiles the message and module regular expressions,
316 and inserts them as a tuple in the list of warnings filters. Entries closer to
317 the front of the list override entries later in the list, if both match a
318 particular warning. Omitted arguments default to a value that matches
319 everything.
320
321
322.. function:: simplefilter(action[, category[, lineno[, append]]])
323
324 Insert a simple entry into the list of warnings filters. The meaning of the
325 function parameters is as for :func:`filterwarnings`, but regular expressions
326 are not needed as the filter inserted always matches any message in any module
327 as long as the category and line number match.
328
329
330.. function:: resetwarnings()
331
332 Reset the warnings filter. This discards the effect of all previous calls to
333 :func:`filterwarnings`, including that of the :option:`-W` command line options
334 and calls to :func:`simplefilter`.
335
Brett Cannon1eaf0742008-09-02 01:25:16 +0000336
Brett Cannon672237d2008-09-09 00:49:16 +0000337Available Context Managers
338--------------------------
Brett Cannon1eaf0742008-09-02 01:25:16 +0000339
Brett Cannon672237d2008-09-09 00:49:16 +0000340.. class:: catch_warnings([\*, record=False, module=None])
Brett Cannon1eaf0742008-09-02 01:25:16 +0000341
Nick Coghland2e09382008-09-11 12:11:06 +0000342 A context manager that copies and, upon exit, restores the warnings filter
343 and the :func:`showwarning` function.
344 If the *record* argument is :const:`False` (the default) the context manager
345 returns :class:`None` on entry. If *record* is :const:`True`, a list is
346 returned that is progressively populated with objects as seen by a custom
347 :func:`showwarning` function (which also suppresses output to ``sys.stdout``).
348 Each object in the list has attributes with the same names as the arguments to
349 :func:`showwarning`.
Brett Cannon1eaf0742008-09-02 01:25:16 +0000350
Brett Cannon672237d2008-09-09 00:49:16 +0000351 The *module* argument takes a module that will be used instead of the
352 module returned when you import :mod:`warnings` whose filter will be
Nick Coghland2e09382008-09-11 12:11:06 +0000353 protected. This argument exists primarily for testing the :mod:`warnings`
Brett Cannon672237d2008-09-09 00:49:16 +0000354 module itself.
Brett Cannon1eaf0742008-09-02 01:25:16 +0000355
356 .. note::
357
358 In Python 3.0, the arguments to the constructor for
359 :class:`catch_warnings` are keyword-only arguments.
360
361 .. versionadded:: 2.6
362