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

Incorrect Undefined Variable for Outer Scope Var #1908

Closed
hmc-cs-mdrissi opened this issue May 25, 2021 · 4 comments
Closed

Incorrect Undefined Variable for Outer Scope Var #1908

hmc-cs-mdrissi opened this issue May 25, 2021 · 4 comments
Labels
as designed Not a bug, working as intended

Comments

@hmc-cs-mdrissi
Copy link

Describe the bug
Variable marked as undefined when coming from an outer scope and then assigned in one branch.

To Reproduce

from typing import Callable, Optional


def f(x: Optional[bool]) -> Callable[[], bool]:
    def g() -> bool:
        if not x:
            x = True
        return x

    return g

Error message, "x" is not defined for the line if not x
Expected behavior
No error.

VS Code extension or command-line
pylance 2021.5.4-pre.1

@JelleZijlstra
Copy link
Contributor

That error is correct. The code will throw an UnboundLocalError at runtime. To fix it, you need to write nonlocal x.

@hmc-cs-mdrissi
Copy link
Author

hmc-cs-mdrissi commented May 25, 2021

That code is simplified part of a unit test that runs successfully. Also the error message goes away if I tweak to

from typing import Callable, Optional

def f(x: Optional[bool]) -> Callable[[], bool]:
    def g() -> bool:
        if not x:
            x_ = True
        else:
          x_ = False
        return x_

    return g


even though that code starts the exact same way.

@JelleZijlstra
Copy link
Contributor

That code is very different, because it creates a separate variable x_ in the inner scope.

@hmc-cs-mdrissi
Copy link
Author

Testing that, that does explain the error.A bit surprised that even though the two examples start the same, the later mutation in first breaks the first access. Reading the nonlocal documentation explains it.

@erictraut erictraut added the as designed Not a bug, working as intended label May 25, 2021
heejaechang added a commit to heejaechang/pyright that referenced this issue Nov 3, 2021
Made completion provider to use newly added getExpectedType + Test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
as designed Not a bug, working as intended
Projects
None yet
Development

No branches or pull requests

3 participants