[flake8-bugbear] Flag mutable defaults passed via named constants (B006)
#21189
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.
Summary
Fixes #21142
B006 now flags mutable defaults passed via module-level named constants. Previously, it only flagged inline mutable defaults (e.g.,
{},[],set()), missing cases where the default references a module-level constant bound to a mutable object (e.g.,MY_SET = {"ABC", "DEF"}).Problem Analysis
B006’s detection was syntax-local and didn’t resolve identifiers to check mutability. When a default used a name like
MY_SET, it wasn’t resolved to the bound mutable object, causing false negatives.Example:
This is a false negative because
func_Aandfunc_Bshare the same mutable default object.Approach
Extended
is_guaranteed_mutable_expr(used in preview mode) to handleExpr::Name:semantic.only_binding()to get the binding.find_binding_value().is_guaranteed_mutable_expr().This enables detecting cases like:
MY_SET = {"ABC", "DEF"}→ flagged when used as a defaultMY_LIST = [1, 2, 3]→ flagged when used as a defaultMY_DICT = {"key": "value"}→ flagged when used as a defaultThe fix is enabled only in preview mode. Non-preview mode preserves existing behavior (only flags inline mutable defaults).