-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[pylint] - implement R0202 and R0203 with autofixes #8335
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
19 changes: 19 additions & 0 deletions
19
crates/ruff_linter/resources/test/fixtures/pylint/no_method_decorator.py
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
from random import choice | ||
|
||
class Fruit: | ||
COLORS = [] | ||
|
||
def __init__(self, color): | ||
self.color = color | ||
|
||
def pick_colors(cls, *args): # [no-classmethod-decorator] | ||
"""classmethod to pick fruit colors""" | ||
cls.COLORS = args | ||
|
||
pick_colors = classmethod(pick_colors) | ||
|
||
def pick_one_color(): # [no-staticmethod-decorator] | ||
"""staticmethod to pick one fruit color""" | ||
return choice(Fruit.COLORS) | ||
|
||
pick_one_color = staticmethod(pick_one_color) |
This file contains 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
This file contains 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
This file contains 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
This file contains 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
202 changes: 202 additions & 0 deletions
202
crates/ruff_linter/src/rules/pylint/rules/no_method_decorator.rs
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,202 @@ | ||
use std::collections::HashMap; | ||
|
||
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, DiagnosticKind, Edit, Fix}; | ||
use ruff_macros::{derive_message_formats, violation}; | ||
use ruff_python_ast::{self as ast, Expr, Stmt}; | ||
use ruff_python_trivia::indentation_at_offset; | ||
use ruff_text_size::{Ranged, TextRange, TextSize}; | ||
|
||
use crate::checkers::ast::Checker; | ||
|
||
/// ## What it does | ||
/// Checks for the use of a classmethod being made without the decorator. | ||
/// | ||
/// ## Why is this bad? | ||
/// When it comes to consistency and readability, it's preferred to use the decorator. | ||
/// | ||
/// ## Example | ||
/// ```python | ||
/// class Foo: | ||
/// def bar(cls): | ||
/// ... | ||
/// | ||
/// bar = classmethod(bar) | ||
/// ``` | ||
/// | ||
/// Use instead: | ||
/// ```python | ||
/// class Foo: | ||
/// @classmethod | ||
/// def bar(cls): | ||
/// ... | ||
/// ``` | ||
#[violation] | ||
pub struct NoClassmethodDecorator; | ||
|
||
impl AlwaysFixableViolation for NoClassmethodDecorator { | ||
#[derive_message_formats] | ||
fn message(&self) -> String { | ||
format!("Class method defined without decorator") | ||
} | ||
|
||
fn fix_title(&self) -> String { | ||
format!("Add @classmethod decorator") | ||
} | ||
} | ||
|
||
/// ## What it does | ||
/// Checks for the use of a staticmethod being made without the decorator. | ||
/// | ||
/// ## Why is this bad? | ||
/// When it comes to consistency and readability, it's preferred to use the decorator. | ||
/// | ||
/// ## Example | ||
/// ```python | ||
/// class Foo: | ||
/// def bar(cls): | ||
/// ... | ||
/// | ||
/// bar = staticmethod(bar) | ||
/// ``` | ||
/// | ||
/// Use instead: | ||
/// ```python | ||
/// class Foo: | ||
/// @staticmethod | ||
/// def bar(cls): | ||
/// ... | ||
/// ``` | ||
#[violation] | ||
pub struct NoStaticmethodDecorator; | ||
|
||
impl AlwaysFixableViolation for NoStaticmethodDecorator { | ||
#[derive_message_formats] | ||
fn message(&self) -> String { | ||
format!("Static method defined without decorator") | ||
} | ||
|
||
fn fix_title(&self) -> String { | ||
format!("Add @staticmethod decorator") | ||
} | ||
} | ||
|
||
enum MethodType { | ||
Classmethod, | ||
Staticmethod, | ||
} | ||
|
||
/// PLR0202 | ||
pub(crate) fn no_classmethod_decorator(checker: &mut Checker, class_def: &ast::StmtClassDef) { | ||
get_undecorated_methods(checker, class_def, &MethodType::Classmethod); | ||
} | ||
|
||
/// PLR0203 | ||
pub(crate) fn no_staticmethod_decorator(checker: &mut Checker, class_def: &ast::StmtClassDef) { | ||
get_undecorated_methods(checker, class_def, &MethodType::Staticmethod); | ||
} | ||
|
||
fn get_undecorated_methods( | ||
checker: &mut Checker, | ||
class_def: &ast::StmtClassDef, | ||
method_type: &MethodType, | ||
) { | ||
let mut explicit_decorator_calls: HashMap<String, TextRange> = HashMap::default(); | ||
|
||
let (method_name, diagnostic_type): (&str, DiagnosticKind) = match method_type { | ||
MethodType::Classmethod => ("classmethod", NoClassmethodDecorator.into()), | ||
MethodType::Staticmethod => ("staticmethod", NoStaticmethodDecorator.into()), | ||
}; | ||
|
||
// gather all explicit *method calls | ||
for stmt in &class_def.body { | ||
if let Stmt::Assign(ast::StmtAssign { targets, value, .. }) = stmt { | ||
if let Expr::Call(ast::ExprCall { | ||
func, arguments, .. | ||
}) = value.as_ref() | ||
{ | ||
if let Expr::Name(ast::ExprName { id, .. }) = func.as_ref() { | ||
if id == method_name && checker.semantic().is_builtin(method_name) { | ||
if arguments.args.len() != 1 { | ||
continue; | ||
} | ||
|
||
if targets.len() != 1 { | ||
continue; | ||
} | ||
|
||
let target_name = match targets.first() { | ||
Some(Expr::Name(ast::ExprName { id, .. })) => id.to_string(), | ||
_ => continue, | ||
}; | ||
|
||
if let Expr::Name(ast::ExprName { id, .. }) = &arguments.args[0] { | ||
if target_name == *id { | ||
explicit_decorator_calls.insert(id.clone(), stmt.range()); | ||
} | ||
}; | ||
} | ||
} | ||
} | ||
}; | ||
} | ||
|
||
if explicit_decorator_calls.is_empty() { | ||
return; | ||
}; | ||
|
||
for stmt in &class_def.body { | ||
if let Stmt::FunctionDef(ast::StmtFunctionDef { | ||
name, | ||
decorator_list, | ||
.. | ||
}) = stmt | ||
{ | ||
if !explicit_decorator_calls.contains_key(name.as_str()) { | ||
continue; | ||
}; | ||
|
||
// if we find the decorator we're looking for, skip | ||
if decorator_list.iter().any(|decorator| { | ||
if let Expr::Name(ast::ExprName { id, .. }) = &decorator.expression { | ||
if id == method_name && checker.semantic().is_builtin(method_name) { | ||
return true; | ||
} | ||
} | ||
|
||
false | ||
}) { | ||
continue; | ||
} | ||
|
||
let mut diagnostic = Diagnostic::new( | ||
diagnostic_type.clone(), | ||
TextRange::new(stmt.range().start(), stmt.range().start()), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't really know what range we should highlight with the diagnostic, please advise! |
||
); | ||
|
||
let indentation = indentation_at_offset(stmt.range().start(), checker.locator()); | ||
|
||
match indentation { | ||
Some(indentation) => { | ||
let range = &explicit_decorator_calls[name.as_str()]; | ||
|
||
// SAFETY: Ruff only supports formatting files <= 4GB | ||
#[allow(clippy::cast_possible_truncation)] | ||
diagnostic.set_fix(Fix::safe_edits( | ||
Edit::insertion( | ||
format!("@{method_name}\n{indentation}"), | ||
stmt.range().start(), | ||
), | ||
[Edit::deletion( | ||
range.start() - TextSize::from(indentation.len() as u32), | ||
range.end(), | ||
)], | ||
)); | ||
checker.diagnostics.push(diagnostic); | ||
} | ||
None => { | ||
continue; | ||
} | ||
}; | ||
}; | ||
} | ||
} |
31 changes: 31 additions & 0 deletions
31
...s/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0202_no_method_decorator.py.snap
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
--- | ||
source: crates/ruff_linter/src/rules/pylint/mod.rs | ||
--- | ||
no_method_decorator.py:9:5: PLR0202 [*] Class method defined without decorator | ||
| | ||
7 | self.color = color | ||
8 | | ||
9 | def pick_colors(cls, *args): # [no-classmethod-decorator] | ||
| PLR0202 | ||
10 | """classmethod to pick fruit colors""" | ||
11 | cls.COLORS = args | ||
| | ||
= help: Add @classmethod decorator | ||
|
||
ℹ Safe fix | ||
6 6 | def __init__(self, color): | ||
7 7 | self.color = color | ||
8 8 | | ||
9 |+ @classmethod | ||
9 10 | def pick_colors(cls, *args): # [no-classmethod-decorator] | ||
10 11 | """classmethod to pick fruit colors""" | ||
11 12 | cls.COLORS = args | ||
12 13 | | ||
13 |- pick_colors = classmethod(pick_colors) | ||
14 14 | | ||
15 |+ | ||
15 16 | def pick_one_color(): # [no-staticmethod-decorator] | ||
16 17 | """staticmethod to pick one fruit color""" | ||
17 18 | return choice(Fruit.COLORS) | ||
|
||
|
27 changes: 27 additions & 0 deletions
27
...s/pylint/snapshots/ruff_linter__rules__pylint__tests__PLR0203_no_method_decorator.py.snap
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
--- | ||
source: crates/ruff_linter/src/rules/pylint/mod.rs | ||
--- | ||
no_method_decorator.py:15:5: PLR0203 [*] Static method defined without decorator | ||
| | ||
13 | pick_colors = classmethod(pick_colors) | ||
14 | | ||
15 | def pick_one_color(): # [no-staticmethod-decorator] | ||
| PLR0203 | ||
16 | """staticmethod to pick one fruit color""" | ||
17 | return choice(Fruit.COLORS) | ||
| | ||
= help: Add @staticmethod decorator | ||
|
||
ℹ Safe fix | ||
12 12 | | ||
13 13 | pick_colors = classmethod(pick_colors) | ||
14 14 | | ||
15 |+ @staticmethod | ||
15 16 | def pick_one_color(): # [no-staticmethod-decorator] | ||
16 17 | """staticmethod to pick one fruit color""" | ||
17 18 | return choice(Fruit.COLORS) | ||
18 19 | | ||
19 |- pick_one_color = staticmethod(pick_one_color) | ||
20 |+ | ||
|
||
|
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would be nice to add some examples here. Personally I don't even know how you define a classmethod without a decorator. 😊
(just a random observer here who's interested in new Pylint rules, thanks for working on this!)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah, my mistake!