-
Notifications
You must be signed in to change notification settings - Fork 903
/
mixed_case_variable_in_class_scope.rs
81 lines (73 loc) · 2.17 KB
/
mixed_case_variable_in_class_scope.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Expr};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::rules::pep8_naming::helpers;
/// ## What it does
/// Checks for class variable names that follow the `mixedCase` convention.
///
/// ## Why is this bad?
/// [PEP 8] recommends that variable names should be lower case and separated
/// by underscores (also known as `snake_case`).
///
/// > Function names should be lowercase, with words separated by underscores
/// as necessary to improve readability.
/// >
/// > Variable names follow the same convention as function names.
/// >
/// > mixedCase is allowed only in contexts where that’s already the
/// prevailing style (e.g. threading.py), to retain backwards compatibility.
///
/// ## Example
/// ```python
/// class MyClass:
/// myVariable = "hello"
/// another_variable = "world"
/// ```
///
/// Use instead:
/// ```python
/// class MyClass:
/// my_variable = "hello"
/// another_variable = "world"
/// ```
///
/// [PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments
#[violation]
pub struct MixedCaseVariableInClassScope {
name: String,
}
impl Violation for MixedCaseVariableInClassScope {
#[derive_message_formats]
fn message(&self) -> String {
let MixedCaseVariableInClassScope { name } = self;
format!("Variable `{name}` in class scope should not be mixedCase")
}
}
/// N815
pub(crate) fn mixed_case_variable_in_class_scope(
checker: &mut Checker,
expr: &Expr,
name: &str,
class_def: &ast::StmtClassDef,
) {
if !helpers::is_mixed_case(name) {
return;
}
let parent = checker.semantic().current_statement();
if helpers::is_named_tuple_assignment(parent, checker.semantic())
|| helpers::is_typed_dict_class(class_def, checker.semantic())
{
return;
}
if checker.settings.pep8_naming.ignore_names.matches(name) {
return;
}
checker.diagnostics.push(Diagnostic::new(
MixedCaseVariableInClassScope {
name: name.to_string(),
},
expr.range(),
));
}