Skip to content

Commit

Permalink
Avoid mutable-class-default violations for Pydantic subclasses (#9187)
Browse files Browse the repository at this point in the history
Only applies to subclasses defined within the same file, as elsewhere.

See:
#5243 (comment).
  • Loading branch information
charliermarsh authored Dec 18, 2023
1 parent c532089 commit 0bf7683
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 16 deletions.
8 changes: 8 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/ruff/RUF012.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,11 @@ class F(BaseSettings):
without_annotation = []
class_variable: ClassVar[list[int]] = []
final_variable: Final[list[int]] = []


class G(F):
mutable_default: list[int] = []
immutable_annotation: Sequence[int] = []
without_annotation = []
class_variable: ClassVar[list[int]] = []
final_variable: Final[list[int]] = []
25 changes: 9 additions & 16 deletions crates/ruff_linter/src/rules/ruff/rules/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use ruff_python_ast::{self as ast, Arguments, Expr};

use ruff_python_ast::helpers::{map_callable, map_subscript};
use ruff_python_semantic::{BindingKind, SemanticModel};
use ruff_python_ast::{self as ast, Expr};
use ruff_python_semantic::{analyze, BindingKind, SemanticModel};

/// Return `true` if the given [`Expr`] is a special class attribute, like `__slots__`.
///
Expand Down Expand Up @@ -57,19 +56,13 @@ pub(super) fn has_default_copy_semantics(
class_def: &ast::StmtClassDef,
semantic: &SemanticModel,
) -> bool {
let Some(Arguments { args: bases, .. }) = class_def.arguments.as_deref() else {
return false;
};

bases.iter().any(|expr| {
semantic.resolve_call_path(expr).is_some_and(|call_path| {
matches!(
call_path.as_slice(),
["pydantic", "BaseModel" | "BaseSettings"]
| ["pydantic_settings", "BaseSettings"]
| ["msgspec", "Struct"]
)
})
analyze::class::any_over_body(class_def, semantic, &|call_path| {
matches!(
call_path.as_slice(),
["pydantic", "BaseModel" | "BaseSettings"]
| ["pydantic_settings", "BaseSettings"]
| ["msgspec", "Struct"]
)
})
}

Expand Down

0 comments on commit 0bf7683

Please sign in to comment.