Fix nested caplog.filtering() removing filter early#14208
Open
Fridayai700 wants to merge 2 commits intopytest-dev:mainfrom
Open
Fix nested caplog.filtering() removing filter early#14208Fridayai700 wants to merge 2 commits intopytest-dev:mainfrom
Fridayai700 wants to merge 2 commits intopytest-dev:mainfrom
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #14189.
When the same filter is used in nested
caplog.filtering()context managers, the inner context's exit callsremoveFilter()which removes the filter entirely — even though the outer context still needs it. This happens becauselogging.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.This is option 1 from the issue — lightweight, no state tracking needed, preserves the existing API contract.