This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Convenient `simplefilter()` in `warnings.catch_warnings()`
Type: enhancement Stage:
Components: Library (Lib) Versions: Python 3.11
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Zac Hatfield-Dodds
Priority: normal Keywords:

Created on 2022-03-21 01:46 by Zac Hatfield-Dodds, last changed 2022-04-11 14:59 by admin.

Messages (1)
msg415647 - (view) Author: Zac Hatfield-Dodds (Zac Hatfield-Dodds) * Date: 2022-03-21 01:46
Many pytest users would like a concise way to either suppress warnings, or convert them to errors [1].  The current best approach is:

    with warnings.catch_warnings():
        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 [2], 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 [3] 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.


[1] see e.g. https://github.com/pytest-dev/pytest/issues/9404 for a long thread
[2] unlike `filterwarnings()`, which has a `module=` argument which would collide with `catch_warnings()`
[3] https://github.com/python/cpython/compare/main...Zac-HD:zac-hd/one-line-catch-warnings
History
Date User Action Args
2022-04-11 14:59:57adminsetgithub: 91230
2022-03-21 01:46:48Zac Hatfield-Doddscreate