Skip to content

Commit 672237d

Browse files
committed
warnings.catch_warnings() now returns a list or None instead of the custom
WarningsRecorder object. This makes the API simpler to use as no special object must be learned. Closes issue 3781. Review by Benjamin Peterson.
1 parent 631be01 commit 672237d

24 files changed

Lines changed: 268 additions & 253 deletions

‎Doc/library/warnings.rst‎

Lines changed: 74 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,67 @@ ImportWarning can also be enabled explicitly in Python code using::
158158
warnings.simplefilter('default', ImportWarning)
159159

160160

161+
.. _warning-suppress:
162+
163+
Temporarily Suppressing Warnings
164+
--------------------------------
165+
166+
If you are using code that you know will raise a warning, such some deprecated
167+
function, but do not want to see the warning, then suppress the warning using
168+
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.
220+
221+
161222
.. _warning-functions:
162223

163224
Available Functions
@@ -264,31 +325,22 @@ Available Functions
264325
and calls to :func:`simplefilter`.
265326

266327

267-
Available Classes
268-
-----------------
269-
270-
.. class:: catch_warnings([\*, record=False[, module=None]])
271-
272-
A context manager that guards the warnings filter from being permanently
273-
mutated. The manager returns an instance of :class:`WarningsRecorder`. The
274-
*record* argument specifies whether warnings that would typically be
275-
handled by :func:`showwarning` should instead be recorded by the
276-
:class:`WarningsRecorder` instance. This argument is typically set when
277-
testing for expected warnings behavior. The *module* argument may be a
278-
module object that is to be used instead of the :mod:`warnings` module.
279-
This argument should only be set when testing the :mod:`warnings` module
280-
or some similar use-case.
328+
Available Context Managers
329+
--------------------------
281330

282-
Typical usage of the context manager is like so::
331+
.. class:: catch_warnings([\*, record=False, module=None])
283332

284-
def fxn():
285-
warn("fxn is deprecated", DeprecationWarning)
286-
return "spam spam bacon spam"
333+
A context manager that copies and, upon exit, restores the warnings filter.
334+
If the *record* argument is False (the default) the context manager returns
335+
:class:`None`. If *record* is true, a list is returned that is populated
336+
with objects as seen by a custom :func:`showwarning` function (which also
337+
suppresses output to ``sys.stdout``). Each object has attributes with the
338+
same names as the arguments to :func:`showwarning`.
287339

288-
# The function 'fxn' is known to raise a DeprecationWarning.
289-
with catch_warnings() as w:
290-
warnings.filterwarning('ignore', 'fxn is deprecated', DeprecationWarning)
291-
fxn() # DeprecationWarning is temporarily suppressed.
340+
The *module* argument takes a module that will be used instead of the
341+
module returned when you import :mod:`warnings` whose filter will be
342+
protected. This arguments exists primarily for testing the :mod:`warnings`
343+
module itself.
292344

293345
.. note::
294346

@@ -297,19 +349,3 @@ Available Classes
297349

298350
.. versionadded:: 2.6
299351

300-
301-
.. class:: WarningsRecorder()
302-
303-
A subclass of :class:`list` that stores all warnings passed to
304-
:func:`showwarning` when returned by a :class:`catch_warnings` context
305-
manager created with its *record* argument set to ``True``. Each recorded
306-
warning is represented by an object whose attributes correspond to the
307-
arguments to :func:`showwarning`. As a convenience, a
308-
:class:`WarningsRecorder` instance has the attributes of the last
309-
recorded warning set on the :class:`WarningsRecorder` instance as well.
310-
311-
.. method:: reset()
312-
313-
Delete all recorded warnings.
314-
315-
.. versionadded:: 2.6

‎Lib/asynchat.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@
5050
import asyncore
5151
from collections import deque
5252
from sys import py3kwarning
53-
from test.test_support import catch_warning
5453
from warnings import filterwarnings, catch_warnings
5554

5655
class async_chat (asyncore.dispatcher):

‎Lib/bsddb/test/test_early_close.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -168,9 +168,9 @@ def test06_close_txn_before_dup_cursor(self) :
168168
self.assertEquals(("XXX", "yyy"), c1.first())
169169
import warnings
170170
# Not interested in warnings about implicit close.
171-
warnings.simplefilter("ignore")
172-
txn.commit()
173-
warnings.resetwarnings()
171+
with warnings.catch_warnings():
172+
warnings.simplefilter("ignore")
173+
txn.commit()
174174
self.assertRaises(db.DBCursorClosedError, c2.first)
175175

176176
if db.version() > (4,3,0) :

‎Lib/mimetools.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import sys
66
import tempfile
77
from warnings import filterwarnings, catch_warnings
8-
with catch_warnings(record=False):
8+
with catch_warnings():
99
if sys.py3kwarning:
1010
filterwarnings("ignore", ".*rfc822 has been removed", DeprecationWarning)
1111
import rfc822

‎Lib/test/test___all__.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import unittest
2-
from test.test_support import run_unittest, catch_warning
2+
from test.test_support import run_unittest
33
import sys
44
import warnings
55

@@ -9,7 +9,7 @@ class AllTest(unittest.TestCase):
99

1010
def check_all(self, modname):
1111
names = {}
12-
with catch_warning():
12+
with warnings.catch_warnings():
1313
warnings.filterwarnings("ignore", ".* (module|package)",
1414
DeprecationWarning)
1515
try:

‎Lib/test/test_exceptions.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
import sys
55
import unittest
66
import pickle, cPickle
7+
import warnings
78

8-
from test.test_support import (TESTFN, unlink, run_unittest,
9-
catch_warning, captured_output)
9+
from test.test_support import TESTFN, unlink, run_unittest, captured_output
1010
from test.test_pep352 import ignore_message_warning
1111

1212
# XXX This is not really enough, each *operation* should be tested!
@@ -274,7 +274,7 @@ def testAttributes(self):
274274
except NameError:
275275
pass
276276

277-
with catch_warning():
277+
with warnings.catch_warnings():
278278
ignore_message_warning()
279279
for exc, args, expected in exceptionList:
280280
try:

‎Lib/test/test_hmac.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ def update(self, v):
211211
def digest(self):
212212
return self._x.digest()
213213

214-
with test_support.catch_warning():
214+
with warnings.catch_warnings():
215215
warnings.simplefilter('error', RuntimeWarning)
216216
try:
217217
hmac.HMAC('a', 'b', digestmod=MockCrazyHash)

‎Lib/test/test_import.py‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import sys
66
import py_compile
77
import warnings
8-
from test.test_support import unlink, TESTFN, unload, run_unittest, catch_warning
8+
from test.test_support import unlink, TESTFN, unload, run_unittest
99

1010

1111
def remove_files(name):
@@ -215,7 +215,7 @@ def test_import_name_binding(self):
215215
self.assert_(y is test.test_support, y.__name__)
216216

217217
def test_import_initless_directory_warning(self):
218-
with catch_warning():
218+
with warnings.catch_warnings():
219219
# Just a random non-package directory we always expect to be
220220
# somewhere in sys.path...
221221
warnings.simplefilter('error', ImportWarning)
@@ -279,17 +279,17 @@ def check_relative():
279279
check_relative()
280280
# Check relative fails with only __package__ wrong
281281
ns = dict(__package__='foo', __name__='test.notarealmodule')
282-
with catch_warning() as w:
282+
with warnings.catch_warnings(record=True) as w:
283283
check_absolute()
284-
self.assert_('foo' in str(w.message))
285-
self.assertEqual(w.category, RuntimeWarning)
284+
self.assert_('foo' in str(w[-1].message))
285+
self.assertEqual(w[-1].category, RuntimeWarning)
286286
self.assertRaises(SystemError, check_relative)
287287
# Check relative fails with __package__ and __name__ wrong
288288
ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
289-
with catch_warning() as w:
289+
with warnings.catch_warnings(record=True) as w:
290290
check_absolute()
291-
self.assert_('foo' in str(w.message))
292-
self.assertEqual(w.category, RuntimeWarning)
291+
self.assert_('foo' in str(w[-1].message))
292+
self.assertEqual(w[-1].category, RuntimeWarning)
293293
self.assertRaises(SystemError, check_relative)
294294
# Check both fail with package set to a non-string
295295
ns = dict(__package__=object())

‎Lib/test/test_macostools.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def compareData(self):
5252
def test_touched(self):
5353
# This really only tests that nothing unforeseen happens.
5454
import warnings
55-
with test_support.catch_warning():
55+
with warnings.catch_warnings():
5656
warnings.filterwarnings('ignore', 'macostools.touched*',
5757
DeprecationWarning)
5858
macostools.touched(test_support.TESTFN)

‎Lib/test/test_pep352.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import __builtin__
33
import exceptions
44
import warnings
5-
from test.test_support import run_unittest, catch_warning
5+
from test.test_support import run_unittest
66
import os
77
from platform import system as platform_system
88

@@ -22,7 +22,7 @@ def test_builtins_new_style(self):
2222
self.failUnless(issubclass(Exception, object))
2323

2424
def verify_instance_interface(self, ins):
25-
with catch_warning():
25+
with warnings.catch_warnings():
2626
ignore_message_warning()
2727
for attr in ("args", "message", "__str__", "__repr__",
2828
"__getitem__"):
@@ -95,7 +95,7 @@ def test_interface_single_arg(self):
9595
# Make sure interface works properly when given a single argument
9696
arg = "spam"
9797
exc = Exception(arg)
98-
with catch_warning():
98+
with warnings.catch_warnings():
9999
ignore_message_warning()
100100
results = ([len(exc.args), 1], [exc.args[0], arg],
101101
[exc.message, arg],
@@ -109,7 +109,7 @@ def test_interface_multi_arg(self):
109109
arg_count = 3
110110
args = tuple(range(arg_count))
111111
exc = Exception(*args)
112-
with catch_warning():
112+
with warnings.catch_warnings():
113113
ignore_message_warning()
114114
results = ([len(exc.args), arg_count], [exc.args, args],
115115
[exc.message, ''], [str(exc), str(args)],
@@ -121,7 +121,7 @@ def test_interface_multi_arg(self):
121121
def test_interface_no_arg(self):
122122
# Make sure that with no args that interface is correct
123123
exc = Exception()
124-
with catch_warning():
124+
with warnings.catch_warnings():
125125
ignore_message_warning()
126126
results = ([len(exc.args), 0], [exc.args, tuple()],
127127
[exc.message, ''],
@@ -132,7 +132,7 @@ def test_interface_no_arg(self):
132132

133133
def test_message_deprecation(self):
134134
# As of Python 2.6, BaseException.message is deprecated.
135-
with catch_warning():
135+
with warnings.catch_warnings():
136136
warnings.resetwarnings()
137137
warnings.filterwarnings('error')
138138

@@ -219,7 +219,7 @@ def test_raise_string(self):
219219

220220
def test_catch_string(self):
221221
# Catching a string should trigger a DeprecationWarning.
222-
with catch_warning():
222+
with warnings.catch_warnings():
223223
warnings.resetwarnings()
224224
warnings.filterwarnings("error")
225225
str_exc = "spam"

0 commit comments

Comments
 (0)