Skip to content
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] removed dunder methods in Python 3 (PLW3201) #13194

Merged
merged 7 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ def __prepare__():
def __mro_entries__(self, bases):
pass

# Deprecated in Python 3
MichaReiser marked this conversation as resolved.
Show resolved Hide resolved
def __unicode__(self):
pass

def __foo_bar__(): # this is not checked by the [bad-dunder-name] rule
...
41 changes: 35 additions & 6 deletions crates/ruff_linter/src/rules/pylint/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,16 @@ impl<'a> Visitor<'_> for SequenceIndexVisitor<'a> {
}
}

/// Returns `true` if a method is a known dunder method.
pub(super) fn is_known_dunder_method(method: &str) -> bool {
matches!(
method,
/// The kind of dunder method.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(super) enum DunderMethodKind {
Known,
Removed,
}

/// Returns the kind of dunder method.
pub(super) fn dunder_method_kind(method: &str) -> Option<DunderMethodKind> {
match method {
"__abs__"
| "__add__"
| "__aenter__"
Expand Down Expand Up @@ -304,6 +310,29 @@ pub(super) fn is_known_dunder_method(method: &str) -> bool {
| "_missing_"
| "_ignore_"
| "_order_"
| "_generate_next_value_"
)
| "_generate_next_value_" => Some(DunderMethodKind::Known),
"__unicode__"
| "__div__"
| "__rdiv__"
| "__idiv__"
| "__nonzero__"
| "__metaclass__"
| "__cmp__"
| "__getslice__"
| "__setslice__"
| "__delslice__"
| "__oct__"
| "__hex__"
| "__members__"
| "__method__"
| "__coerce__"
| "__long__"
| "__rcmp__" => Some(DunderMethodKind::Removed),
_ => None,
}
}

/// Returns `true` if a method is a known dunder method.
pub(super) fn is_known_dunder_method(method: &str) -> bool {
dunder_method_kind(method) == Some(DunderMethodKind::Known)
}
41 changes: 30 additions & 11 deletions crates/ruff_linter/src/rules/pylint/rules/bad_dunder_method_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,19 @@ use ruff_python_ast::identifier::Identifier;
use ruff_python_semantic::analyze::visibility;

use crate::checkers::ast::Checker;
use crate::rules::pylint::helpers::is_known_dunder_method;
use crate::rules::pylint::helpers::{dunder_method_kind, DunderMethodKind};

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum Kind {
Misspelled,
RemovedInPython3,
}

/// ## What it does
/// Checks for misspelled and unknown dunder names in method definitions.
/// Checks for misspelled, unknown and no longer supported dunder names in method definitions.
///
/// ## Why is this bad?
/// Misspelled dunder name methods may cause your code to not function
/// Misspelled or no longer supported dunder name methods may cause your code to not function
/// as expected.
///
/// Since dunder methods are associated with customizing the behavior
Expand Down Expand Up @@ -45,13 +51,19 @@ use crate::rules::pylint::helpers::is_known_dunder_method;
#[violation]
pub struct BadDunderMethodName {
name: String,
kind: Kind,
}

impl Violation for BadDunderMethodName {
#[derive_message_formats]
fn message(&self) -> String {
let BadDunderMethodName { name } = self;
format!("Bad or misspelled dunder method name `{name}`")
let BadDunderMethodName { name, kind } = self;
match kind {
Kind::Misspelled => format!("Bad or misspelled dunder method name `{name}`"),
Kind::RemovedInPython3 => {
format!("Python 2 or older only dunder method name `{name}`")
Copy link
Member

Choose a reason for hiding this comment

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

@AlexWaygood any suggestion on how to improve the wording here? It's kind of hard to read

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think removing the 'only' makes it read a bit smoother, but it might change the meaning slightly.

Copy link
Member

@AlexWaygood AlexWaygood Sep 3, 2024

Choose a reason for hiding this comment

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

Maybe something like this?

Suggested change
format!("Python 2 or older only dunder method name `{name}`")
format!("Dunder method `{name}` has no special meaning in Python 3")

Though actually, that's a pretty good description of what the problem is in both cases. I wonder if we need to distinguish between misspelled dunder methods and those that were removed in Python 3 at all, or if we could just improve the docs (like this PR already does) and use a better error message here that applies to both cases? In both cases -- whether you've misspelled a dunder or you're using one that had its special semantics removed in Python 3 -- it's not going to cause any kind of exception to define the dunder method. It's just probably not going to do what you want, because it doesn't have any special semantics attached to it anymore.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Way clearer!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@MichaReiser What do you think about a single message for both cases?

Copy link
Member

Choose a reason for hiding this comment

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

A bit dissatisfying after all the hard work you put into this but I do like the suggested message.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No problem, I also agree 😄

}
}
}
}

Expand All @@ -63,12 +75,11 @@ pub(crate) fn bad_dunder_method_name(checker: &mut Checker, method: &ast::StmtFu
}

// If the name is explicitly allowed, skip it.
if is_known_dunder_method(&method.name)
|| checker
.settings
.pylint
.allow_dunder_method_names
.contains(method.name.as_str())
if checker
.settings
.pylint
.allow_dunder_method_names
.contains(method.name.as_str())
|| matches!(method.name.as_str(), "_")
{
return;
Expand All @@ -78,9 +89,17 @@ pub(crate) fn bad_dunder_method_name(checker: &mut Checker, method: &ast::StmtFu
return;
}

// If the method is known, skip it.
let kind = match dunder_method_kind(&method.name) {
Some(DunderMethodKind::Known) => return,
Some(DunderMethodKind::Removed) => Kind::RemovedInPython3,
None => Kind::Misspelled,
};

checker.diagnostics.push(Diagnostic::new(
BadDunderMethodName {
name: method.name.to_string(),
kind,
},
method.identifier(),
));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,10 @@ bad_dunder_method_name.py:23:9: PLW3201 Bad or misspelled dunder method name `__
25 | pass
|


bad_dunder_method_name.py:98:9: PLW3201 Python 2 or older only dunder method name `__unicode__`
|
97 | # Deprecated in Python 3
MichaReiser marked this conversation as resolved.
Show resolved Hide resolved
98 | def __unicode__(self):
| ^^^^^^^^^^^ PLW3201
99 | pass
|
Loading