diff options
author | Zac Hatfield-Dodds <zac.hatfield.dodds@gmail.com> | 2022-04-24 00:55:22 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-04-24 00:55:22 (GMT) |
commit | b4e048411f4c62ad7343bca32c307f0bf5ef74b4 (patch) | |
tree | 5bf8f8dca04efab3796b05952dee9035bf9f72b8 /Lib/warnings.py | |
parent | 692e9078a10b268530f8da7d3095cfb05c48435b (diff) | |
download | cpython-b4e048411f4c62ad7343bca32c307f0bf5ef74b4.zip cpython-b4e048411f4c62ad7343bca32c307f0bf5ef74b4.tar.gz cpython-b4e048411f4c62ad7343bca32c307f0bf5ef74b4.tar.bz2 |
gh-91230: Concise catch_warnings with simplefilter (#91435)
Diffstat (limited to 'Lib/warnings.py')
-rw-r--r-- | Lib/warnings.py | 12 |
1 files changed, 11 insertions, 1 deletions
diff --git a/Lib/warnings.py b/Lib/warnings.py index 887ca6e..7d8c440 100644 --- a/Lib/warnings.py +++ b/Lib/warnings.py @@ -432,9 +432,13 @@ class catch_warnings(object): named 'warnings' and imported under that name. This argument is only useful when testing the warnings module itself. + If the 'action' argument is not None, the remaining arguments are passed + to warnings.simplefilter() as if it were called immediately on entering the + context. """ - def __init__(self, *, record=False, module=None): + def __init__(self, *, record=False, module=None, + action=None, category=Warning, lineno=0, append=False): """Specify whether to record warnings and if an alternative module should be used other than sys.modules['warnings']. @@ -445,6 +449,10 @@ class catch_warnings(object): self._record = record self._module = sys.modules['warnings'] if module is None else module self._entered = False + if action is None: + self._filter = None + else: + self._filter = (action, category, lineno, append) def __repr__(self): args = [] @@ -464,6 +472,8 @@ class catch_warnings(object): self._module._filters_mutated() self._showwarning = self._module.showwarning self._showwarnmsg_impl = self._module._showwarnmsg_impl + if self._filter is not None: + simplefilter(*self._filter) if self._record: log = [] self._module._showwarnmsg_impl = log.append |