Skip to content

Commit

Permalink
Fix false-positive in RET504 when referencing globals
Browse files Browse the repository at this point in the history
Closes #1310
  • Loading branch information
squiddy committed Dec 24, 2022
1 parent 4ded155 commit 0d9b802
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
12 changes: 12 additions & 0 deletions resources/test/fixtures/flake8_return/RET504.py
Expand Up @@ -237,3 +237,15 @@ def close(self):
any_failed = True
report(traceback.format_exc())
return any_failed

def global_assignment():
global X
X = 1
return X

def nonlocal_assignment():
X = 1
def inner():
nonlocal X
X = 1
return X
4 changes: 4 additions & 0 deletions src/flake8_return/plugins.rs
Expand Up @@ -203,6 +203,10 @@ fn unnecessary_assign(checker: &mut Checker, stack: &Stack, expr: &Expr) {
return;
}

if stack.non_locals.contains(id.as_str()) {
return;
}

checker.add_check(Check::new(
CheckKind::UnnecessaryAssign,
Range::from_located(expr),
Expand Down
8 changes: 7 additions & 1 deletion src/flake8_return/visitor.rs
@@ -1,4 +1,4 @@
use rustc_hash::FxHashMap;
use rustc_hash::{FxHashMap, FxHashSet};
use rustpython_ast::{Expr, ExprKind, Location, Stmt, StmtKind};

use crate::ast::visitor;
Expand All @@ -10,6 +10,7 @@ pub struct Stack<'a> {
pub ifs: Vec<&'a Stmt>,
pub elifs: Vec<&'a Stmt>,
pub refs: FxHashMap<&'a str, Vec<Location>>,
pub non_locals: FxHashSet<&'a str>,
pub assigns: FxHashMap<&'a str, Vec<Location>>,
pub loops: Vec<(Location, Location)>,
pub tries: Vec<(Location, Location)>,
Expand Down Expand Up @@ -48,6 +49,11 @@ impl<'a> ReturnVisitor<'a> {
impl<'a> Visitor<'a> for ReturnVisitor<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
match &stmt.node {
StmtKind::Global { names } | StmtKind::Nonlocal { names } => {
self.stack
.non_locals
.extend(names.iter().map(std::string::String::as_str));
}
StmtKind::FunctionDef { .. } | StmtKind::AsyncFunctionDef { .. } => {
// Don't recurse.
}
Expand Down

0 comments on commit 0d9b802

Please sign in to comment.