-
Notifications
You must be signed in to change notification settings - Fork 883
/
getattr_with_constant.rs
109 lines (103 loc) · 3.17 KB
/
getattr_with_constant.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use crate::autofix::edits::pad;
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Constant, Expr};
use ruff_python_stdlib::identifiers::{is_identifier, is_mangled_private};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
use crate::registry::AsRule;
/// ## What it does
/// Checks for uses of `getattr` that take a constant attribute value as an
/// argument (e.g., `getattr(obj, "foo")`).
///
/// ## Why is this bad?
/// `getattr` is used to access attributes dynamically. If the attribute is
/// defined as a constant, it is no safer than a typical property access. When
/// possible, prefer property access over `getattr` calls, as the former is
/// more concise and idiomatic.
///
///
/// ## Example
/// ```python
/// getattr(obj, "foo")
/// ```
///
/// Use instead:
/// ```python
/// obj.foo
/// ```
///
/// ## References
/// - [Python documentation: `getattr`](https://docs.python.org/3/library/functions.html#getattr)
#[violation]
pub struct GetAttrWithConstant;
impl AlwaysAutofixableViolation for GetAttrWithConstant {
#[derive_message_formats]
fn message(&self) -> String {
format!(
"Do not call `getattr` with a constant attribute value. It is not any safer than \
normal property access."
)
}
fn autofix_title(&self) -> String {
"Replace `getattr` with attribute access".to_string()
}
}
/// B009
pub(crate) fn getattr_with_constant(
checker: &mut Checker,
expr: &Expr,
func: &Expr,
args: &[Expr],
) {
let Expr::Name(ast::ExprName { id, .. }) = func else {
return;
};
if id != "getattr" {
return;
}
let [obj, arg] = args else {
return;
};
if obj.is_starred_expr() {
return;
}
let Expr::Constant(ast::ExprConstant {
value: Constant::Str(ast::StringConstant { value, .. }),
..
}) = arg
else {
return;
};
if !is_identifier(value) {
return;
}
if is_mangled_private(value) {
return;
}
if !checker.semantic().is_builtin("getattr") {
return;
}
let mut diagnostic = Diagnostic::new(GetAttrWithConstant, expr.range());
if checker.patch(diagnostic.kind.rule()) {
diagnostic.set_fix(Fix::suggested(Edit::range_replacement(
pad(
if matches!(
obj,
Expr::Name(_) | Expr::Attribute(_) | Expr::Subscript(_) | Expr::Call(_)
) {
format!("{}.{}", checker.locator().slice(obj), value)
} else {
// Defensively parenthesize any other expressions. For example, attribute accesses
// on `int` literals must be parenthesized, e.g., `getattr(1, "real")` becomes
// `(1).real`. The same is true for named expressions and others.
format!("({}).{}", checker.locator().slice(obj), value)
},
expr.range(),
checker.locator(),
),
expr.range(),
)));
}
checker.diagnostics.push(diagnostic);
}