Skip to content

Commit 4edb4c7

Browse files
committed
Fix: Add type check for category in warning.simplefilter & warning.filterwarnings
1 parent d1d5dce commit 4edb4c7

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

Lib/_py_warnings.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,11 @@ def _formatwarnmsg(msg):
250250
msg.filename, msg.lineno, msg.line)
251251
return _wm._formatwarnmsg_impl(msg)
252252

253+
def _valid_warning_category(category):
254+
"""Return True if category is a Warning subclass or tuple of such."""
255+
if isinstance(category, tuple):
256+
return all(isinstance(c, type) and issubclass(c, Warning) for c in category)
257+
return isinstance(category, type) and issubclass(category, Warning)
253258

254259
def filterwarnings(action, message="", category=Warning, module="", lineno=0,
255260
append=False):
@@ -267,8 +272,9 @@ def filterwarnings(action, message="", category=Warning, module="", lineno=0,
267272
raise ValueError(f"invalid action: {action!r}")
268273
if not isinstance(message, str):
269274
raise TypeError("message must be a string")
270-
if not isinstance(category, type) or not issubclass(category, Warning):
271-
raise TypeError("category must be a Warning subclass")
275+
if not _valid_warning_category(category):
276+
raise TypeError("category must be a Warning subclass, "
277+
"not '{:s}'".format(type(category).__name__))
272278
if not isinstance(module, str):
273279
raise TypeError("module must be a string")
274280
if not isinstance(lineno, int):
@@ -303,6 +309,9 @@ def simplefilter(action, category=Warning, lineno=0, append=False):
303309
"""
304310
if action not in {"error", "ignore", "always", "all", "default", "module", "once"}:
305311
raise ValueError(f"invalid action: {action!r}")
312+
if not _valid_warning_category(category):
313+
raise TypeError("category must be a Warning subclass, "
314+
"not '{:s}'".format(type(category).__name__))
306315
if not isinstance(lineno, int):
307316
raise TypeError("lineno must be an int")
308317
if lineno < 0:

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2149,5 +2149,6 @@ Jelle Zijlstra
21492149
Gennadiy Zlobin
21502150
Doug Zongker
21512151
Peter Åstrand
2152+
Hasrat Ali Arzoo
21522153

21532154
(Entries should be added in rough alphabetical order by last names)

0 commit comments

Comments
 (0)