Improve handling of metaclasses in various linter rules #12579
Merged
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
This PR does several interrelated things:
is_metaclass
function out ofcrates/ruff_linter/src/rules/flake8_pyi/rules/non_self_return_type.rs
and into theruff_python_semantic
crate. It's a generally useful function, and we were doing similar analysis elsewhere (but we were doing it incorrectly). It's better to centralize it in one place.classify()
function inruff_python_semantic::analyze::function_type
so that it no longer reports that metaclass instance methods are classmethods. For ourpep8-naming
rules, it makes sense to treat metaclass instance methods like classmethods, since metaclass instance methods usually usecls
for the name of the first parameter, like classmethods on non-metaclasses. However, theclassify()
function is used by many other linter rules, not just ourpep8-naming
rules. For those rules, it doesn't make sense for metaclass instance methods to be considered classmethods, since, well, they're not. An example is B019, which I've added a test for in this PR: I'm not sure it makes sense to treat instance methods on metaclasses any differently to instance methods on regular classes for that rule.ruff_python_semantic::analyze::function_type::classify()
no longer considers instance methods on metaclasses to be classmethods, I adjusted thepep8-naming
rules so that they now do their own check to see whether an instance method is a method on a metaclass, in order to determine what the name of the first parameter should be.FWIW, there were several buggy things in the check for metaclasses that
ruff_python_semantic::analyze::function_type::classify()
was doing:map_callable()
when it should have been usingmap_subscript()
enum
-module metaclasses that the stdlib providesTest Plan
cargo test -p ruff_linter