Repository navigation
warnings.catch_warnings is not thread safe or async safe #128384
Copy link
Copy link
Closed
Labels
stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytopic-asynciotopic-free-threadingtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
Description
Activity
- addedtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or errorstdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directory
on Dec 31, 2024 - added a commit that references this issue
on Mar 11, 2025 Fixed by GH-130010. You have to set the
sys.flags.context_aware_warningsflag to ensure you get the new behavior. If you are using threads, you will want to setsys.flags.thread_inherit_contextas well.
Metadata
Metadata
Assignees
Labels
stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytopic-asynciotopic-free-threadingtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
Projects
- StatusShow more project fieldsDone
Bug report
Bug description:
This is an old issue but it has become more urgent to fix given free-threaded Python. A simple example to show how the current context manager can fail:
Since
test_warning()is running in separate threads, there is no consistent ordering of which context manager exits first. That means the filters value that gets restored is also not consistent (a race between the threads about which version of the filters value they will restore).The context manager is also not friendly to async code. These issues have been reported before:
The fairly obvious fix to this issue is to use
contextvars, similar to how thedecimalmodule uses a context. This is both thread safe and friendly to async code.The
warningsmodule itself has some "shallow" thread safety issues but these are relatively easy to fix and no API changes are needed.CPython versions tested on:
CPython main branch
Operating systems tested on:
Linux
Linked PRs