Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

[ruff] Guard against use of default_factory as a keyword argument (RUF026) #9651

Conversation

mikeleppane
Copy link
Contributor

@mikeleppane mikeleppane commented Jan 26, 2024

Summary

Add a rule for defaultdict(default_factory=callable). Instead suggest using defaultdict(callable).

See: #9509

If a user tries to bind a "non-callable" to default_factory, the rule ignores it. Another option would be to warn that it's probably not what you want. Because Python allows the following:

from collections import defaultdict

defaultdict(default_factory=1)

this raises after you actually try to use it:

dd = defaultdict(default_factory=1)
dd[1]

=>

KeyError: 1

Instead using callable directly in the constructor it will raise (not being a callable):

from collections import defaultdict

defaultdict(1)

=>

TypeError: first argument must be callable or None

Test Plan

cargo test

Copy link
Contributor

github-actions bot commented Jan 26, 2024

ruff-ecosystem results

Linter (stable)

✅ ecosystem check detected no linter changes.

Linter (preview)

✅ ecosystem check detected no linter changes.

@charliermarsh charliermarsh added rule Implementing or modifying a lint rule preview Related to preview mode features labels Jan 26, 2024
@charliermarsh charliermarsh self-requested a review January 26, 2024 15:51
Copy link
Member

@charliermarsh charliermarsh left a comment

Choose a reason for hiding this comment

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

Thanks!

@charliermarsh charliermarsh force-pushed the feat(RUF026)/add-rule-for-defaultdict-with-defaulf-factory branch from b5775b8 to 86881c7 Compare January 26, 2024 19:03
@charliermarsh charliermarsh force-pushed the feat(RUF026)/add-rule-for-defaultdict-with-defaulf-factory branch from 86881c7 to b805448 Compare January 26, 2024 19:04
@charliermarsh charliermarsh changed the title [ruff]: Prefer using defaultdict(callable) instead of initializing with default_factory=callable (RUF026) [ruff] Guard against use of default_factory as a keyword argument (RUF026) Jan 26, 2024
@charliermarsh charliermarsh enabled auto-merge (squash) January 26, 2024 19:04
@charliermarsh charliermarsh enabled auto-merge (squash) January 26, 2024 19:05
@charliermarsh charliermarsh merged commit d496c16 into astral-sh:main Jan 26, 2024
16 checks passed
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
preview Related to preview mode features rule Implementing or modifying a lint rule
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants