Skip to content

Fix nested caplog.filtering() removing filter early#14208

Open
Fridayai700 wants to merge 2 commits intopytest-dev:mainfrom
Fridayai700:fix-caplog-filtering-nested
Open

Fix nested caplog.filtering() removing filter early#14208
Fridayai700 wants to merge 2 commits intopytest-dev:mainfrom
Fridayai700:fix-caplog-filtering-nested

Conversation

@Fridayai700
Copy link

Fixes #14189.

When the same filter is used in nested caplog.filtering() context managers, the inner context's exit calls removeFilter() which removes the filter entirely — even though the outer context still needs it. This happens because logging.Handler.removeFilter() works by identity.

Fix: Before adding a filter, check if it's already present on the handler (from an outer filtering() call). If so, skip both the add and remove, leaving the outer scope's lifecycle in control.

# Before fix: third warning is incorrectly captured
with caplog.filtering(no_capture):
    logging.warning("filtered")       # not captured ✓
    with caplog.filtering(no_capture):
        logging.warning("filtered")   # not captured ✓
    logging.warning("should be filtered")  # captured ✗ (filter was removed)

# After fix: all three warnings inside outer scope are filtered

This is option 1 from the issue — lightweight, no state tracking needed, preserves the existing API contract.

When the same filter was used in nested `caplog.filtering()` context
managers, the inner context's exit would call `removeFilter()` which
removes the filter entirely — even though the outer context still needs
it. This happened because `removeFilter()` works by identity/value.

Fix by checking if the filter is already present before adding. If it
was already attached (from an outer scope), skip both the add and the
remove, leaving the outer scope's lifecycle in control.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@psf-chronographer psf-chronographer bot added the bot:chronographer:provided (automation) changelog entry is part of PR label Feb 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided (automation) changelog entry is part of PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Nested caplog.filtering usage may remove filters early

1 participant

Comments