pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

False Positive [unbound-name] with walrus operator

Open randolf-scholz opened this issue 6 months ago • 2 comments

Describe the Bug

def demo(text: str) -> None:
    [text := text.replace(s, f"\\{s}") for s in "&#" if s in text];
ERROR sandbox.py:2:14-18: `text` is uninitialized [unbound-name]

Python: 3.12

Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeSImMYABFQLa4AUALjPi4jXCwE4CUNALQA%2BGgDlc6GIgA66GopoBtNhxqIAvDTUtCvGMSioAxjCZwANDTCyQsh7OBwAvncFhcvbjQgK7AGQAxHa%2BtHC%2BCroAugDc8iCWIGQGYFCkhCy49FAUQTQACqSp6dwYOAQ0JlKQAOYArryoLBBShPL5AMowMDQAFiwsxHCIAPSjKdTphF61ozDoo5i4JnCj1eh1jc2tizZeNKgAbqjQqNiwVTUQDU0tUjS4xPfocO3oZCx9UkJHMLxwXY0bR2ADMhAAjAAmOzyZT-XheODReT1dAQejELxsTBCTAQAwmFp-YE0ADkN3QXhgZPkVJYQgMAEd6gSYLiANYwUhCUxmOARbRkgDuqF46Fp6BALiSpmJMAAYtAYBQ0Fg8EQyNKgA

(Only applicable for extension issues) IDE Information

No response

randolf-scholz avatar May 14 '26 12:05 randolf-scholz

Hi, I'd like to work on this issue.

The bug is that pyrefly reports text as uninitialized in a list comprehension with a walrus operator, even though it's defined as a function parameter. This is a false positive - Python allows using the walrus operator (:=) in comprehension filters to reference variables from the outer scope.

I'll start by creating a failing test, then investigate the binding/solving phase to find where the scope handling for walrus operators needs to be fixed.

f1sherFM avatar May 15 '26 16:05 f1sherFM

Hi! I've prepared a fix for this issue.

Changes:

  • Fixed look_up_name_for_read in scope.rs to check enclosing scopes before returning static lookup from comprehension scope. This fixes false positive "X is uninitialized" errors when walrus operator (:=) in comprehension filter reads a variable from the enclosing function scope.
  • Added test case reproducing the bug to prevent regressions.

PR will be submitted in ~5 hours: f1sherFM/pyrefly#fix-issue-3398

Feedback is welcome! 🙏

f1sherFM avatar May 16 '26 11:05 f1sherFM