[New-bugs-announce] [issue47074] Convenient `simplefilter()` in `warnings.catch_warnings()`
report at bugs.python.org
Sun Mar 20 21:46:48 EDT 2022
New submission from Zac Hatfield-Dodds <zac.hatfield.dodds at gmail.com>:
Many pytest users would like a concise way to either suppress warnings, or convert them to errors . The current best approach is:
warnings.simplefilter("ignore") # or "error"
but even this becomes tediously verbose when repeated in hundreds of tests (which I suspect is responsible for many misuses of `pytest.raises()`). Since these two functions take disjoint arguments , I propose allowing catch_warnings() to accept arguments for simplefilter() and forward them on:
with warnings.catch_warnings("ignore"): # or "error"
I have a quick implementation at  which I can finish if the idea is acceptable. Although I don't have a concrete use-case for more than the 'action' and 'category' arguments, forwarding all rather than some makes the semantics very simple.
I'd emphasize again that this is very much a convenience-focussed change: I estimate that 95% of all uses will pass only `action="error"` or `action="ignore"`. Supporting a concise and simple interface for this seems worth the small complication to the design of the warnings module.
 see e.g. https://github.com/pytest-dev/pytest/issues/9404 for a long thread
 unlike `filterwarnings()`, which has a `module=` argument which would collide with `catch_warnings()`
components: Library (Lib)
nosy: Zac Hatfield-Dodds
title: Convenient `simplefilter()` in `warnings.catch_warnings()`
versions: Python 3.11
Python tracker <report at bugs.python.org>
More information about the New-bugs-announce