Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/pyflakes/F821_34.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from __future__ import annotations

from typing import Callable


def demonstrate_bare_local_annotation():
x: int
print(x)
Comment on lines +6 to +8
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still haven't looked too closely at this, but I agree that it's unfortunate not to flag this case. It might be worth looking into how ty handles this since it seems to get the expected result in both cases:

https://play.ty.dev/c6f45910-a2bd-4745-827b-f29a148f4e63

It doesn't seem to be related to nonlocal, though, because commenting it out doesn't change ty's diagnostics.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One option to do this is then something like

                    BindingKind::Annotation if !self.in_stub_file() => {
                        if self.scopes[self.bindings[binding_id].scope]
                            .kind
                            .is_function()
                        {
                            // If we're in a function scope, and the annotation is local to that scope,
                            // treat it as unbound (since it's not assigned).
                            // If it's an enclosing scope, we treat it as resolved (to support closures).
                            if index == 0 {
                                self.unresolved_references.push(
                                    name.range,
                                    self.exceptions(),
                                    UnresolvedReferenceFlags::empty(),
                                );
                                return ReadResult::UnboundLocal(binding_id);
                            }
                            
                            self.resolved_names.insert(name.into(), binding_id);
                            return ReadResult::Resolved(binding_id);
                        
                        }
                        continue;
                    }

if we do this then both the cases will be handled i.e. error in this case

def demonstrate_bare_local_annotation():
    x: int
    print(x)

and no error in the closure cases i.e. the setter,getter example

but then again we will have edge cases like these where no error will be reported [although even ty doesn't report them]

def demo_closure():
    x: int
    def func():
        return x

What do you think about this


demonstrate_bare_local_annotation()


def make_closure_pair() -> tuple[Callable[[], int], Callable[[int], None]]:
x: int

def get_value() -> int:
return x

def set_value(new_value: int) -> None:
nonlocal x
x = new_value

return get_value, set_value

get_value, set_value = make_closure_pair()
set_value(123)
print(get_value())
3 changes: 2 additions & 1 deletion crates/ruff_linter/src/rules/pyflakes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ mod tests {
#[test_case(Rule::UndefinedName, Path::new("F821_31.py"))]
#[test_case(Rule::UndefinedName, Path::new("F821_32.pyi"))]
#[test_case(Rule::UndefinedName, Path::new("F821_33.py"))]
#[test_case(Rule::UndefinedName, Path::new("F821_34.py"))]
#[test_case(Rule::UndefinedExport, Path::new("F822_0.py"))]
#[test_case(Rule::UndefinedExport, Path::new("F822_0.pyi"))]
#[test_case(Rule::UndefinedExport, Path::new("F822_1.py"))]
Expand Down Expand Up @@ -3663,7 +3664,7 @@ lambda: fu
name: str
print(name)
",
&[Rule::UndefinedName],
&[],
);
flakes(
r"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
source: crates/ruff_linter/src/rules/pyflakes/mod.rs
---

16 changes: 13 additions & 3 deletions crates/ruff_python_semantic/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -475,9 +475,19 @@ impl<'a> SemanticModel<'a> {
// The `name` in `print(name)` should be treated as unresolved, but the `name` in
// `name: str` should be treated as used.
//
// Stub files are an exception. In a stub file, it _is_ considered valid to
// resolve to a type annotation.
BindingKind::Annotation if !self.in_stub_file() => continue,
// There are two exceptions to this rule:
// 1. Stub files. In a stub file, it _is_ considered valid to resolve to a
// type annotation.
// 2. Bare annotations inside functions. Per PEP 526, these create local
// variables.
BindingKind::Annotation
if !self.in_stub_file()
&& !self.scopes[self.bindings[binding_id].scope]
.kind
.is_function() =>
{
continue;
}

// If it's a deletion, don't treat it as resolved, since the name is now
// unbound. For example, given:
Expand Down