Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix false-positive in RET504 when referencing globals #1358

Merged
merged 1 commit into from Dec 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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