blob: f6856ff7213ccd1c4f2ddfc2a0228eb1ff9ca7e1 [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
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000168If you are using code that you know will raise a warning, such as a deprecated
169function, but do not want to see the warning, then it is possible to suppress
170the warning using the :class:`catch_warnings` context manager::
Brett Cannon1cd02472008-09-09 01:52:27 +0000171
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
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000221results. The :func:`showwarning` function in the module is also restored to
222its original value.
223
224When testing multiple operations that raise the same kind of warning, it
225is important to test them in a manner that confirms each operation is raising
226a new warning (e.g. set warnings to be raised as exceptions and check the
227operations raise exceptions, check that the length of the warning list
228continues to increase after each operation, or else delete the previous
229entries from the warnings list before each new operation).
Brett Cannon1cd02472008-09-09 01:52:27 +0000230
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232.. _warning-functions:
233
234Available Functions
235-------------------
236
237
238.. function:: warn(message[, category[, stacklevel]])
239
240 Issue a warning, or maybe ignore it or raise an exception. The *category*
241 argument, if given, must be a warning category class (see above); it defaults to
242 :exc:`UserWarning`. Alternatively *message* can be a :exc:`Warning` instance,
243 in which case *category* will be ignored and ``message.__class__`` will be used.
244 In this case the message text will be ``str(message)``. This function raises an
245 exception if the particular warning issued is changed into an error by the
246 warnings filter see above. The *stacklevel* argument can be used by wrapper
247 functions written in Python, like this::
248
249 def deprecation(message):
250 warnings.warn(message, DeprecationWarning, stacklevel=2)
251
252 This makes the warning refer to :func:`deprecation`'s caller, rather than to the
253 source of :func:`deprecation` itself (since the latter would defeat the purpose
254 of the warning message).
255
256
257.. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]])
258
259 This is a low-level interface to the functionality of :func:`warn`, passing in
260 explicitly the message, category, filename and line number, and optionally the
261 module name and the registry (which should be the ``__warningregistry__``
262 dictionary of the module). The module name defaults to the filename with
263 ``.py`` stripped; if no registry is passed, the warning is never suppressed.
264 *message* must be a string and *category* a subclass of :exc:`Warning` or
265 *message* may be a :exc:`Warning` instance, in which case *category* will be
266 ignored.
267
268 *module_globals*, if supplied, should be the global namespace in use by the code
269 for which the warning is issued. (This argument is used to support displaying
Christian Heimes3279b5d2007-12-09 15:58:13 +0000270 source for modules found in zipfiles or other non-filesystem import
271 sources).
Georg Brandl116aa622007-08-15 14:28:22 +0000272
273
Christian Heimes33fe8092008-04-13 13:53:33 +0000274.. function:: showwarning(message, category, filename, lineno[, file[, line]])
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276 Write a warning to a file. The default implementation calls
Christian Heimes33fe8092008-04-13 13:53:33 +0000277 ``formatwarning(message, category, filename, lineno, line)`` and writes the
278 resulting string to *file*, which defaults to ``sys.stderr``. You may replace
279 this function with an alternative implementation by assigning to
Georg Brandl116aa622007-08-15 14:28:22 +0000280 ``warnings.showwarning``.
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000281 *line* is a line of source code to be included in the warning
Georg Brandl48310cd2009-01-03 21:18:54 +0000282 message; if *line* is not supplied, :func:`showwarning` will
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000283 try to read the line specified by *filename* and *lineno*.
Georg Brandl116aa622007-08-15 14:28:22 +0000284
285
Christian Heimes33fe8092008-04-13 13:53:33 +0000286.. function:: formatwarning(message, category, filename, lineno[, line])
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288 Format a warning the standard way. This returns a string which may contain
Georg Brandl48310cd2009-01-03 21:18:54 +0000289 embedded newlines and ends in a newline. *line* is
290 a line of source code to be included in the warning message; if *line* is not supplied,
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000291 :func:`formatwarning` will try to read the line specified by *filename* and *lineno*.
Georg Brandl116aa622007-08-15 14:28:22 +0000292
293
294.. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]])
295
296 Insert an entry into the list of warnings filters. The entry is inserted at the
297 front by default; if *append* is true, it is inserted at the end. This checks
298 the types of the arguments, compiles the message and module regular expressions,
299 and inserts them as a tuple in the list of warnings filters. Entries closer to
300 the front of the list override entries later in the list, if both match a
301 particular warning. Omitted arguments default to a value that matches
302 everything.
303
304
305.. function:: simplefilter(action[, category[, lineno[, append]]])
306
307 Insert a simple entry into the list of warnings filters. The meaning of the
308 function parameters is as for :func:`filterwarnings`, but regular expressions
309 are not needed as the filter inserted always matches any message in any module
310 as long as the category and line number match.
311
312
313.. function:: resetwarnings()
314
315 Reset the warnings filter. This discards the effect of all previous calls to
316 :func:`filterwarnings`, including that of the :option:`-W` command line options
317 and calls to :func:`simplefilter`.
318
Brett Cannonec92e182008-09-02 02:46:59 +0000319
Brett Cannon1cd02472008-09-09 01:52:27 +0000320Available Context Managers
321--------------------------
Brett Cannonec92e182008-09-02 02:46:59 +0000322
323.. class:: catch_warnings([\*, record=False, module=None])
324
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000325 A context manager that copies and, upon exit, restores the warnings filter
326 and the :func:`showwarning` function.
327 If the *record* argument is :const:`False` (the default) the context manager
328 returns :class:`None` on entry. If *record* is :const:`True`, a list is
329 returned that is progressively populated with objects as seen by a custom
330 :func:`showwarning` function (which also suppresses output to ``sys.stdout``).
331 Each object in the list has attributes with the same names as the arguments to
332 :func:`showwarning`.
Brett Cannonec92e182008-09-02 02:46:59 +0000333
Brett Cannon1cd02472008-09-09 01:52:27 +0000334 The *module* argument takes a module that will be used instead of the
335 module returned when you import :mod:`warnings` whose filter will be
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000336 protected. This argument exists primarily for testing the :mod:`warnings`
Brett Cannon1cd02472008-09-09 01:52:27 +0000337 module itself.