Skip to content

Commit

Permalink
fix: avoid flagging unused loop variable (B007) with globals(), vars(…
Browse files Browse the repository at this point in the history
…) or eval()

Issue astral-sh#2161
  • Loading branch information
spaceone committed Jan 25, 2023
1 parent 6978dcf commit 0c14f8c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
11 changes: 11 additions & 0 deletions resources/test/fixtures/flake8_bugbear/B007.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,14 @@ def strange_generator():
for foo, bar in [(1, 2)]:
if foo:
print(FMT.format(**locals()))

for foo, bar in [(1, 2)]:
if foo:
print(FMT.format(**globals()))

for foo, bar in [(1, 2)]:
if foo:
print(FMT.format(**vars()))

for foo, bar in [(1, 2)]:
print(FMT.format(foo=foo, bar=eval('bar')))
7 changes: 4 additions & 3 deletions src/ast/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -562,12 +562,13 @@ pub fn is_super_call_with_arguments(func: &Expr, args: &[Expr]) -> bool {
}
}

/// Return `true` if the body uses `locals()`.
pub fn uses_locals(body: &[Stmt]) -> bool {
/// Return `true` if the body uses `locals()`, `globals()`, `vars()`, `eval()`.
pub fn uses_magic_variable_access(body: &[Stmt]) -> bool {
any_over_body(body, &|expr| {
if let ExprKind::Call { func, .. } = &expr.node {
if let ExprKind::Name { id, ctx } = &func.node {
id == "locals" && matches!(ctx, ExprContext::Load)
["locals", "globals", "vars", "eval"].contains(&id.as_str())
&& matches!(ctx, ExprContext::Load)
} else {
false
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ where

/// B007
pub fn unused_loop_control_variable(checker: &mut Checker, target: &Expr, body: &[Stmt]) {
if helpers::uses_locals(body) {
if helpers::uses_magic_variable_access(body) {
return;
}

Expand Down

0 comments on commit 0c14f8c

Please sign in to comment.