Skip to content

Commit

Permalink
[flake8-django] Recognize other magic methods (DJ012) (#15365)
Browse files Browse the repository at this point in the history
  • Loading branch information
InSyncWithFoo authored Jan 9, 2025
1 parent bf5b0c2 commit 8bc11c4
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,11 @@ def __str__(self):

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): ...
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -131,7 +132,7 @@ enum ContentType {
FieldDeclaration,
ManagerDeclaration,
MetaClass,
StrMethod,
MagicMethod,
SaveMethod,
GetAbsoluteUrlMethod,
CustomMethod,
Expand All @@ -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"),
Expand Down Expand Up @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down

0 comments on commit 8bc11c4

Please sign in to comment.