Skip to content

logging.captureWarnings and warnings.catch_warnings do not play well together #139355

@braingram

Description

@braingram

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 #130010) the second example (enabling captureWarnings outside the catch_warnings) no longer works.

CPython versions tested on:

3.13

Operating systems tested on:

macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions