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

Skip class scopes when resolving nonlocal references #4943

Merged
merged 1 commit into from
Jun 7, 2023
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
19 changes: 19 additions & 0 deletions crates/ruff/resources/test/fixtures/pyflakes/F841_0.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,22 @@ def f(x: int):
def f():
if any((key := (value := x)) for x in ["ok"]):
print(key)


def f() -> None:
is_connected = False

class Foo:
@property
def is_connected(self):
nonlocal is_connected
return is_connected

def do_thing(self):
# This should resolve to the `is_connected` in the function scope.
nonlocal is_connected
print(is_connected)

obj = Foo()
obj.do_thing()

4 changes: 2 additions & 2 deletions crates/ruff/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,14 +291,14 @@ where
}

// Mark the binding in the defining scopes as used too. (Skip the global scope
// and the current scope.)
// and the current scope, and, per standard resolution rules, any class scopes.)
for (name, range) in names.iter().zip(ranges.iter()) {
let binding_id = self
.semantic_model
.scopes
.ancestors(self.semantic_model.scope_id)
.skip(1)
.take_while(|scope| !scope.kind.is_module())
.filter(|scope| !(scope.kind.is_module() || scope.kind.is_class()))
.find_map(|scope| scope.get(name.as_str()));

if let Some(binding_id) = binding_id {
Expand Down