[flake8-django] Recognize other magic methods (DJ012) (#15365)

This commit is contained in:
InSync 2025-01-09 20:36:42 +07:00 committed by GitHub
parent bf5b0c2688
commit 8bc11c49b2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 13 additions and 4 deletions

View file

@ -145,3 +145,11 @@ class StrBeforeFieldInheritedModel(BaseModel):
first_name = models.CharField(max_length=32)
# https://github.com/astral-sh/ruff/issues/13892
class DunderMethodOtherThanStrBeforeSave(models.Model):
name = models.CharField()
def __init__(self, *args, **kwargs): ...
def save(*args, **kwargs): ...

View file

@ -2,6 +2,7 @@ use std::fmt;
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, ViolationMetadata};
use ruff_python_ast::helpers::is_dunder;
use ruff_python_ast::{self as ast, Expr, Stmt};
use ruff_python_semantic::{Modules, SemanticModel};
use ruff_text_size::Ranged;
@ -131,7 +132,7 @@ enum ContentType {
FieldDeclaration,
ManagerDeclaration,
MetaClass,
StrMethod,
MagicMethod,
SaveMethod,
GetAbsoluteUrlMethod,
CustomMethod,
@ -143,7 +144,7 @@ impl fmt::Display for ContentType {
ContentType::FieldDeclaration => f.write_str("field declaration"),
ContentType::ManagerDeclaration => f.write_str("manager declaration"),
ContentType::MetaClass => f.write_str("`Meta` class"),
ContentType::StrMethod => f.write_str("`__str__` method"),
ContentType::MagicMethod => f.write_str("Magic method"),
ContentType::SaveMethod => f.write_str("`save` method"),
ContentType::GetAbsoluteUrlMethod => f.write_str("`get_absolute_url` method"),
ContentType::CustomMethod => f.write_str("custom method"),
@ -177,7 +178,7 @@ fn get_element_type(element: &Stmt, semantic: &SemanticModel) -> Option<ContentT
}
}
Stmt::FunctionDef(ast::StmtFunctionDef { name, .. }) => match name.as_str() {
"__str__" => Some(ContentType::StrMethod),
name if is_dunder(name) => Some(ContentType::MagicMethod),
"save" => Some(ContentType::SaveMethod),
"get_absolute_url" => Some(ContentType::GetAbsoluteUrlMethod),
_ => Some(ContentType::CustomMethod),

View file

@ -18,7 +18,7 @@ DJ012.py:43:5: DJ012 Order of model's inner classes, methods, and fields does no
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ DJ012
|
DJ012.py:56:5: DJ012 Order of model's inner classes, methods, and fields does not follow the Django Style Guide: `__str__` method should come before custom method
DJ012.py:56:5: DJ012 Order of model's inner classes, methods, and fields does not follow the Django Style Guide: Magic method should come before custom method
|
54 | pass
55 |