python / python/cpython

`logging.captureWarnings` and `warnings.catch_warnings` do not play well together

Open
#139,355 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

When logging.captureWarnings(True) is called within a warnings.catch_warnings(record=True) context warnings emitted during the context are not recorded.

import logging, warnings
with warnings.catch_warnings(record=True) as rec:
    logging.captureWarnings(True)
    warnings.warn("foo")
assert len(rec) == 1  # fails since len(rec) == 0

one work-around for this is to enable captureWarnings outside the context

import logging, warnings
logging.captureWarnings(True)
with warnings.catch_warnings(record=True) as rec:
    warnings.warn("foo")
assert len(rec) == 1

I tested the above examples on 3.10, 3.13 and 3.14.0b2.

However on 3.14.0b2 with PYTHON_CONTEXT_AWARE_WARNINGS=1 (to pull in the changes from https://github.com/python/cpython/pull/130010) the second example (enabling captureWarnings outside the catch_warnings) no longer works.

CPython versions tested on:

3.13

Operating systems tested on:

macOS

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the examples using logging.captureWarnings(True) with warnings.catch_warnings(record=True), including PYTHON_CONTEXT_AWARE_WARNINGS=1. Trace the interaction between these two APIs and verify that warnings emitted in the context are recorded in both configurations described by the report.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.