rest25/library/warnings.rst => rest262/library/warnings.rst
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
n19-in this module.  (C programmers use :cfunc:`PyErr_Warn`; see the Python/C API
n19+in this module.  (C programmers use :cfunc:`PyErr_WarnEx`; see
20-Reference Manual (XXX reference: ../api/exceptionHandling.html) for details).
20+: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
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)
n159+ 
160+ 
161+.. _warning-suppress:
162+ 
163+Temporarily Suppressing Warnings
164+--------------------------------
165+ 
166+If you are using code that you know will raise a warning, such as a deprecated
167+function, but do not want to see the warning, then it is possible to suppress
168+the warning using the :class:`catch_warnings` context manager::
169+ 
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+ 
179+While within the context manager all warnings will simply be ignored. This
180+allows you to use known-deprecated code without having to see the warning while
181+not suppressing the warning for other code that might not be aware of its use
182+of deprecated code.
183+ 
184+ 
185+.. _warning-testing:
186+ 
187+Testing Warnings
188+----------------
189+ 
190+To test warnings raised by code, use the :class:`catch_warnings` context
191+manager. With it you can temporarily mutate the warnings filter to facilitate
192+your testing. For instance, do the following to capture all raised warnings to
193+check::
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+ 
210+One 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
212+raised because of a ``once``/``default`` rule, then no matter what filters are
213+set the warning will not be seen again unless the warnings registry related to
214+the warning has been cleared.
215+ 
216+Once the context manager exits, the warnings filter is restored to its state
217+when the context was entered. This prevents tests from changing the warnings
218+filter in unexpected ways between tests and leading to indeterminate test
219+results. The :func:`showwarning` function in the module is also restored to
220+its original value.
221+ 
222+When testing multiple operations that raise the same kind of warning, it
223+is important to test them in a manner that confirms each operation is raising
224+a new warning (e.g. set warnings to be raised as exceptions and check the
225+operations raise exceptions, check that the length of the warning list
226+continues to increase after each operation, or else delete the previous
227+entries from the warnings list before each new operation).
159
160
161.. _warning-functions:
162
163Available Functions
164-------------------
165
166
191   dictionary of the module).  The module name defaults to the filename with
192   ``.py`` stripped; if no registry is passed, the warning is never suppressed.
193   *message* must be a string and *category* a subclass of :exc:`Warning` or
194   *message* may be a :exc:`Warning` instance, in which case *category* will be
195   ignored.
196
197   *module_globals*, if supplied, should be the global namespace in use by the code
198   for which the warning is issued.  (This argument is used to support displaying
n199-   source for modules found in zipfiles or other non-filesystem import sources, and
n268+   source for modules found in zipfiles or other non-filesystem import
200-   was added in Python 2.5.)
269+   sources).
201
n271+   .. versionchanged:: 2.5
272+      Added the *module_globals* parameter.
202
n274+ 
275+.. function:: warnpy3k(message[, category[, stacklevel]])
276+ 
277+   Issue a warning related to Python 3.x deprecation. Warnings are only shown
278+   when Python is started with the -3 option. Like :func:`warn` *message* must
279+   be a string and *category* a subclass of :exc:`Warning`. :func:`warnpy3k`
280+   is using :exc:`DeprecationWarning` as default warning class.
281+ 
282+ 
203-.. function:: showwarning(message, category, filename, lineno[, file])
283+.. function:: showwarning(message, category, filename, lineno[, file[, line]])
204
205   Write a warning to a file.  The default implementation calls
n206-   ``formatwarning(message, category, filename, lineno)`` and writes the resulting
n286+   ``formatwarning(message, category, filename, lineno, line)`` and writes the
207-   string to *file*, which defaults to ``sys.stderr``.  You may replace this
287+   resulting string to *file*, which defaults to ``sys.stderr``.  You may replace
208-   function with an alternative implementation by assigning to
288+   this function with an alternative implementation by assigning to
209   ``warnings.showwarning``.
n290+   *line* is a line of source code to be included in the warning
291+   message; if *line* is not supplied, :func:`showwarning` will
292+   try to read the line specified by *filename* and *lineno*.
210
n294+   .. versionchanged:: 2.6
295+      Added the *line* argument. Implementations that lack the new argument
296+      will trigger a :exc:`DeprecationWarning`.
211
n298+ 
212-.. function:: formatwarning(message, category, filename, lineno)
299+.. function:: formatwarning(message, category, filename, lineno[, line])
213
214   Format a warning the standard way.  This returns a string  which may contain
n215-   embedded newlines and ends in a newline.
n302+   embedded newlines and ends in a newline.  *line* is
303+   a line of source code to be included in the warning message; if *line* is not supplied,
304+   :func:`formatwarning` will try to read the line specified by *filename* and *lineno*.
305+ 
306+   .. versionchanged:: 2.6
307+      Added the *line* argument.
216
217
218.. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]])
219
220   Insert an entry into the list of warnings filters.  The entry is inserted at the
221   front by default; if *append* is true, it is inserted at the end. This checks
222   the types of the arguments, compiles the message and module regular expressions,
223   and inserts them as a tuple in the  list of warnings filters.  Entries closer to
235
236
237.. function:: resetwarnings()
238
239   Reset the warnings filter.  This discards the effect of all previous calls to
240   :func:`filterwarnings`, including that of the :option:`-W` command line options
241   and calls to :func:`simplefilter`.
242
t335+ 
336+Available Context Managers
337+--------------------------
338+ 
339+.. class:: catch_warnings([\*, record=False, module=None])
340+ 
341+    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`.
349+ 
350+    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
352+    protected. This argument exists primarily for testing the :mod:`warnings`
353+    module itself.
354+ 
355+    .. note::
356+ 
357+        In Python 3.0, the arguments to the constructor for
358+        :class:`catch_warnings` are keyword-only arguments.
359+ 
360+    .. versionadded:: 2.6
361+ 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op