Skip to content

Commit

Permalink
Avoid some false positives in dunder variable assigments (#4508)
Browse files Browse the repository at this point in the history
  • Loading branch information
scop committed May 19, 2023
1 parent d4c0a41 commit 2e2ba2c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 12 deletions.
2 changes: 1 addition & 1 deletion crates/ruff/resources/test/fixtures/pycodestyle/E402.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
else:
import e

y = x + 1
__some__magic = 1

import f

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ source: crates/ruff/src/rules/pycodestyle/mod.rs
---
E402.py:24:1: E402 Module level import not at top of file
|
24 | y = x + 1
24 | __some__magic = 1
25 |
26 | import f
| ^^^^^^^^ E402
Expand Down
24 changes: 14 additions & 10 deletions crates/ruff_python_ast/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ use std::path::Path;
use itertools::Itertools;
use log::error;
use num_traits::Zero;
use once_cell::sync::Lazy;
use regex::Regex;
use ruff_text_size::{TextRange, TextSize};
use rustc_hash::{FxHashMap, FxHashSet};
use rustpython_parser::ast::{
Expand Down Expand Up @@ -542,7 +540,9 @@ where
body.iter().any(|stmt| any_over_stmt(stmt, func))
}

static DUNDER_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"__[^\s]+__").unwrap());
fn is_dunder(id: &str) -> bool {
id.starts_with("__") && id.ends_with("__")
}

/// Return `true` if the [`Stmt`] is an assignment to a dunder (like `__all__`).
pub fn is_assignment_to_a_dunder(stmt: &Stmt) -> bool {
Expand All @@ -553,15 +553,19 @@ pub fn is_assignment_to_a_dunder(stmt: &Stmt) -> bool {
if targets.len() != 1 {
return false;
}
match &targets[0] {
Expr::Name(ast::ExprName { id, .. }) => DUNDER_REGEX.is_match(id.as_str()),
_ => false,
if let Expr::Name(ast::ExprName { id, .. }) = &targets[0] {
is_dunder(id)
} else {
false
}
}
Stmt::AnnAssign(ast::StmtAnnAssign { target, .. }) => {
if let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() {
is_dunder(id)
} else {
false
}
}
Stmt::AnnAssign(ast::StmtAnnAssign { target, .. }) => match target.as_ref() {
Expr::Name(ast::ExprName { id, .. }) => DUNDER_REGEX.is_match(id.as_str()),
_ => false,
},
_ => false,
}
}
Expand Down

0 comments on commit 2e2ba2c

Please sign in to comment.