Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 52a7d98

Browse files
committed
Make warnings accept a callable for showwarnings instead of
restricting itself to just functions and methods (which allows built-in functions to be used, etc.). Closes issue #10271. Thanks to lekma for the bug report.
1 parent b05be7d commit 52a7d98

2 files changed

Lines changed: 10 additions & 8 deletions

File tree

Lib/test/test_warnings.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -512,12 +512,11 @@ def test_showwarning_missing(self):
512512
def test_showwarning_not_callable(self):
513513
with original_warnings.catch_warnings(module=self.module):
514514
self.module.filterwarnings("always", category=UserWarning)
515-
old_showwarning = self.module.showwarning
515+
self.module.showwarning = print
516+
with support.captured_output('stdout'):
517+
self.module.warn('Warning!')
516518
self.module.showwarning = 23
517-
try:
518-
self.assertRaises(TypeError, self.module.warn, "Warning!")
519-
finally:
520-
self.module.showwarning = old_showwarning
519+
self.assertRaises(TypeError, self.module.warn, "Warning!")
521520

522521
def test_show_warning_output(self):
523522
# With showarning() missing, make sure that output is okay.
@@ -547,10 +546,13 @@ def test_filename_none(self):
547546
globals_dict = globals()
548547
oldfile = globals_dict['__file__']
549548
try:
550-
with original_warnings.catch_warnings(module=self.module) as w:
549+
catch = original_warnings.catch_warnings(record=True,
550+
module=self.module)
551+
with catch as w:
551552
self.module.filterwarnings("always", category=UserWarning)
552553
globals_dict['__file__'] = None
553554
original_warnings.warn('test', UserWarning)
555+
self.assertTrue(len(w))
554556
finally:
555557
globals_dict['__file__'] = oldfile
556558

Python/_warnings.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -409,10 +409,10 @@ warn_explicit(PyObject *category, PyObject *message,
409409
else {
410410
PyObject *res;
411411

412-
if (!PyMethod_Check(show_fxn) && !PyFunction_Check(show_fxn)) {
412+
if (!PyCallable_Check(show_fxn)) {
413413
PyErr_SetString(PyExc_TypeError,
414414
"warnings.showwarning() must be set to a "
415-
"function or method");
415+
"callable");
416416
Py_DECREF(show_fxn);
417417
goto cleanup;
418418
}

0 commit comments

Comments
 (0)