Skip to content

Treat more collections and weakref containers as mutable - #29213

Merged
ntBre merged 4 commits into
astral-sh:mainfrom
shan3520:b006-weakref-mutable-defaults
Oct 14, 2026
Merged

ntBre merged 4 commits into
astral-sh:mainfrom
shan3520:b006-weakref-mutable-defaults

Conversation

@shan3520

@shan3520 shan3520 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #25173

This PR changes behavior of flake8-bugbear in regard to weakref.WeakKeyDictionary, weakref.WeakValueDictionary, weakref.WeakSet, collections.ChainMap, collections.UserDict, collections.UserList, and collections.UserString, so that instead of reporting the error B008 ("function call in argument defaults"), it reports B006 ("mutable data structures for argument defaults"). These types are similar to dict and list in terms of being containers and are considered to be mutable, and therefore are suitable for B006, allowing for fixing the code via replacing a default value with None and making the object construction inside the body of the function.

Implementation details

In this PR, those seven types are added to is_mutable_return_type in crates/ruff_python_stdlib/src/typing.rs file along with other types like dict, list, set, Counter, OrderedDict, defaultdict, and deque. As B008 purposefully skips objects matching is_mutable_return_type condition, this solves the categorization mistake while avoiding duplicates.

As discussed with maintainers, this change doesn't use --preview option. Because is_mutable_return_type is a shared helper, another side effect of this PR is that B039, RUF008, RUF012, RUF024, and PLW2901 rules will also treat those seven types as mutable data structures. According to the review comments, collections.UserList and collections.UserString are also included; even though str is immutable, a UserString instance is mutable due to .data attribute being reassignable.

Test Plan

A new mdtest was added at crates/ruff_linter/resources/mdtest/flake8-bugbear/mutable-argument-default.md.

The new mdtest is set up to generate results for B006 and B008 and to include a single import case per type. The purpose of the test is to verify that B006 is triggered and that B008 ignores all those seven types strictly.

No ruff_linter snapshot changes in the existing tests. Ecosystem check results come from CI.

@shan3520
shan3520 marked this pull request as ready for review October 8, 2026 07:00
@astral-sh-bot
astral-sh-bot Bot requested a review from ntBre October 8, 2026 07:00
@astral-sh-bot

astral-sh-bot Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

ecosystem-analyzer results

No diagnostic changes detected ✅

Flaky changes detected. This PR summary excludes flaky changes; see the HTML report for details.

Full report with detailed diff (timing results)

@astral-sh-bot

astral-sh-bot Bot commented Oct 9, 2026

Copy link
Copy Markdown

ruff-ecosystem results

Linter (stable)

✅ ecosystem check detected no linter changes.

Linter (preview)

✅ ecosystem check detected no linter changes.

Comment on lines +123 to +124
|| (is_b006_weakref_types_enabled(self.checker.settings())
&& is_weakref_mutable_func(map_subscript(func), self.checker.semantic()));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's not worry about preview here. I think it's fine just to add the new types to this function:

/// Returns `true` if a call path represents a function from the Python standard library that
/// returns a mutable value (e.g., `dict`).
pub fn is_mutable_return_type(qualified_name: &[&str]) -> bool {
matches!(
qualified_name,
["" | "builtins", "dict" | "list" | "set"]
| [
"collections",
"Counter" | "OrderedDict" | "defaultdict" | "deque"
]
)
}

I think we should go ahead and handle the additional collections types mentioned in the follow-up comment here too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. I have stripped the preview logic and just inserted the weakref classes into is_mutable_return_type. As you suggested, I also included ChainMap and UserDict (the two items on jonathandung's playground post). In contrast, I have avoided adding UserString because it just wraps an immutable string data type. Just a small question - Should I be including UserList while I am at it? Even though it is mutable, but I didn't consider including it explicitly since it was not in the original issue report.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, I think it makes sense to include UserList as well. I think UserString could actually be worth including too. Even though the str is immutable, the UserString instance is mutable through the data attribute:

>>> from collections import UserString
...
... def f(value=UserString("")):
...     value.data += "x"
...     return str(value)
...
>>> f()
'x'
>>> f()
'xx'

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Completed in d705cec—Added both UserList and UserString to is_mutable_return_type under the collections group. The reason why UserString should be treated like that is absolutely obvious – while the underlying str is immutable, the data attribute of this instance can be changed making a default value like UserString("") to persist from call to another, just like in your example with 'x' and 'xx' return values of f(). Also made mdtest add collections.UserList() and collections.UserString(""), expecting both to give B006.

Comment on lines +1 to +11
import weakref
from weakref import WeakKeyDictionary, WeakSet, WeakValueDictionary
import weakref as wr


def weakref_module(
a=weakref.WeakKeyDictionary(),
b=weakref.WeakValueDictionary(),
c=weakref.WeakSet(),
):
pass

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we trim these down (and ideally use a new mdtest)? Other fixtures should already test from imports and aliases. I don't think we need to repeat that coverage here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. I have deleted the entire fixture file B006_10.py along with four generated snapshots. Instead of that, I have created one simple mdtest (resources/mdtest/flake8-bugbear/mutable-argument-default.md) which only considers one 'plain import' case for each type without generating all combinations of aliases. This mdtest chooses both B006 and B008 which makes sure we continue testing B008 is not raised here anymore.

@ntBre ntBre added the rule Implementing or modifying a lint rule label Oct 9, 2026
…ict` as mutable data structures (`B006`)
@shan3520 shan3520 changed the title [flake8-bugbear] Treat weakref containers as mutable data structures (B006) [flake8-bugbear] Consider weakref containers, ChainMap and UserDict as mutable containers (B006) Oct 9, 2026
@shan3520 shan3520 changed the title [flake8-bugbear] Consider weakref containers, ChainMap and UserDict as mutable containers (B006) [flake8-bugbear] Treat more collections and weakref containers as mutable data structures (B006) Oct 14, 2026
@ntBre ntBre changed the title [flake8-bugbear] Treat more collections and weakref containers as mutable data structures (B006) Treat more collections and weakref containers as mutable Oct 14, 2026

@ntBre ntBre left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@ntBre
ntBre enabled auto-merge (squash) October 14, 2026 15:33
@ntBre
ntBre merged commit 523d83c into astral-sh:main Oct 14, 2026
58 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

rule Implementing or modifying a lint rule

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Raise B006 rather than B008 for data structures such as weakref.WeakKeyDictionary and weakref.WeakValueDictionary

2 participants