~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Doc/library/warnings.rst

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 
 
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
Warning messages are typically issued in situations where it is useful to alert
 
12
the user of some condition in a program, where that condition (normally) doesn't
 
13
warrant raising an exception and terminating the program.  For example, one
 
14
might want to issue a warning when a program uses an obsolete module.
 
15
 
 
16
Python programmers issue warnings by calling the :func:`warn` function defined
 
17
in this module.  (C programmers use :cfunc:`PyErr_WarnEx`; see
 
18
:ref:`exceptionhandling` for details).
 
19
 
 
20
Warning messages are normally written to ``sys.stderr``, but their disposition
 
21
can be changed flexibly, from ignoring all warnings to turning them into
 
22
exceptions.  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
 
24
is issued.  Repetitions of a particular warning for the same source location are
 
25
typically suppressed.
 
26
 
 
27
There are two stages in warning control: first, each time a warning is issued, a
 
28
determination is made whether a message should be issued or not; next, if a
 
29
message is to be issued, it is formatted and printed using a user-settable hook.
 
30
 
 
31
The determination whether to issue a warning message is controlled by the
 
32
warning filter, which is a sequence of matching rules and actions. Rules can be
 
33
added to the filter by calling :func:`filterwarnings` and reset to its default
 
34
state by calling :func:`resetwarnings`.
 
35
 
 
36
The printing of warning messages is done by calling :func:`showwarning`, which
 
37
may be overridden; the default implementation of this function formats the
 
38
message by calling :func:`formatwarning`, which is also available for use by
 
39
custom implementations.
 
40
 
 
41
 
 
42
.. _warning-categories:
 
43
 
 
44
Warning Categories
 
45
------------------
 
46
 
 
47
There are a number of built-in exceptions that represent warning categories.
 
48
This categorization is useful to be able to filter out groups of warnings.  The
 
49
following 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
+----------------------------------+-----------------------------------------------+
 
83
| :exc:`BytesWarning`              | Base category for warnings related to         |
 
84
|                                  | :class:`bytes` and :class:`buffer`.           |
 
85
+----------------------------------+-----------------------------------------------+
 
86
 
 
87
 
 
88
While these are technically built-in exceptions, they are documented here,
 
89
because conceptually they belong to the warnings mechanism.
 
90
 
 
91
User code can define additional warning categories by subclassing one of the
 
92
standard warning categories.  A warning category must always be a subclass of
 
93
the :exc:`Warning` class.
 
94
 
 
95
 
 
96
.. _warning-filter:
 
97
 
 
98
The Warnings Filter
 
99
-------------------
 
100
 
 
101
The warnings filter controls whether warnings are ignored, displayed, or turned
 
102
into errors (raising an exception).
 
103
 
 
104
Conceptually, the warnings filter maintains an ordered list of filter
 
105
specifications; any specific warning is matched against each filter
 
106
specification in the list in turn until a match is found; the match determines
 
107
the 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
 
 
145
Since the :exc:`Warning` class is derived from the built-in :exc:`Exception`
 
146
class, to turn a warning into an error we simply raise ``category(message)``.
 
147
 
 
148
The warnings filter is initialized by :option:`-W` options passed to the Python
 
149
interpreter 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
 
152
are ignored, after printing a message to ``sys.stderr``).
 
153
 
 
154
The warnings that are ignored by default may be enabled by passing :option:`-Wd`
 
155
to the interpreter. This enables default handling for all warnings, including
 
156
those that are normally ignored by default. This is particular useful for
 
157
enabling ImportWarning when debugging problems importing a developed package.
 
158
ImportWarning can also be enabled explicitly in Python code using::
 
159
 
 
160
   warnings.simplefilter('default', ImportWarning)
 
161
 
 
162
 
 
163
.. _warning-suppress:
 
164
 
 
165
Temporarily Suppressing Warnings
 
166
--------------------------------
 
167
 
 
168
If you are using code that you know will raise a warning, such as a deprecated
 
169
function, but do not want to see the warning, then it is possible to suppress
 
170
the warning using the :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
 
 
181
While within the context manager all warnings will simply be ignored. This
 
182
allows you to use known-deprecated code without having to see the warning while
 
183
not suppressing the warning for other code that might not be aware of its use
 
184
of deprecated code.
 
185
 
 
186
 
 
187
.. _warning-testing:
 
188
 
 
189
Testing Warnings
 
190
----------------
 
191
 
 
192
To test warnings raised by code, use the :class:`catch_warnings` context
 
193
manager. With it you can temporarily mutate the warnings filter to facilitate
 
194
your testing. For instance, do the following to capture all raised warnings to
 
195
check::
 
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
 
 
212
One 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
 
214
raised because of a ``once``/``default`` rule, then no matter what filters are
 
215
set the warning will not be seen again unless the warnings registry related to
 
216
the warning has been cleared.
 
217
 
 
218
Once the context manager exits, the warnings filter is restored to its state
 
219
when the context was entered. This prevents tests from changing the warnings
 
220
filter in unexpected ways between tests and leading to indeterminate test
 
221
results. The :func:`showwarning` function in the module is also restored to
 
222
its original value.
 
223
 
 
224
When testing multiple operations that raise the same kind of warning, it
 
225
is important to test them in a manner that confirms each operation is raising
 
226
a new warning (e.g. set warnings to be raised as exceptions and check the
 
227
operations raise exceptions, check that the length of the warning list
 
228
continues to increase after each operation, or else delete the previous
 
229
entries from the warnings list before each new operation).
 
230
 
 
231
 
 
232
.. _warning-functions:
 
233
 
 
234
Available 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
 
270
   source for modules found in zipfiles or other non-filesystem import
 
271
   sources).
 
272
 
 
273
 
 
274
.. function:: showwarning(message, category, filename, lineno[, file[, line]])
 
275
 
 
276
   Write a warning to a file.  The default implementation calls
 
277
   ``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
 
280
   ``warnings.showwarning``.
 
281
   *line* is a line of source code to be included in the warning
 
282
   message; if *line* is not supplied, :func:`showwarning` will
 
283
   try to read the line specified by *filename* and *lineno*.
 
284
 
 
285
 
 
286
.. function:: formatwarning(message, category, filename, lineno[, line])
 
287
 
 
288
   Format a warning the standard way.  This returns a string  which may contain
 
289
   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,
 
291
   :func:`formatwarning` will try to read the line specified by *filename* and *lineno*.
 
292
 
 
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
 
 
319
 
 
320
Available Context Managers
 
321
--------------------------
 
322
 
 
323
.. class:: catch_warnings([\*, record=False, module=None])
 
324
 
 
325
    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`.
 
333
 
 
334
    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
 
336
    protected. This argument exists primarily for testing the :mod:`warnings`
 
337
    module itself.