Skip to content

PEP 572: re-use of variable defined with assignment expression / walrus operator not permitted #9096

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

Closed
dhood opened this issue Jul 5, 2020 · 2 comments
Labels
topic-pep-572 PEP 572 (walrus operator)

Comments

@dhood
Copy link
Contributor

dhood commented Jul 5, 2020

There is special handling of variables defined using a named expression from within comprehensions (See https://www.python.org/dev/peps/pep-0572/#scope-of-the-target). This has been implemented in #8053 and updated in #9062

I think that is what's causing this issue with re-definition of such variables:

# walrus_fail_demo.py
def func() -> None:
    l = [0, 1, 2]
    filtered_data = [new_elem for elem in l if (new_elem := 1) is not None]
    filtered_data = [new_elem for elem in l if (new_elem := 1) is not None]

(since #9062 it is also possible to use this list comprehension from outside of the function scope, it will fail the same way)

Expected behaviour: re-definition of the new_v variable is allowed by mypy and adapted to.

Observed behaviour using version: 0.790+dev.8219564d365ba29dda8c4383594d9db91f26feec:

walrus_fail_demo.py:4: error: Name 'new_v' already defined on line 3
@Akuli
Copy link
Contributor

Akuli commented Oct 25, 2021

No longer errors on master:

(env310) akuli@akuli-desktop:~/mypy$ cat >a.py
def func() -> None:
    l = [0, 1, 2]
    filtered_data = [new_elem for elem in l if (new_elem := 1) is not None]
    filtered_data = [new_elem for elem in l if (new_elem := 1) is not None]

(env310) akuli@akuli-desktop:~/mypy$ python3 -m mypy a.py
Success: no issues found in 1 source file

@emmatyping
Copy link
Member

Confirmed as fixed in master.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic-pep-572 PEP 572 (walrus operator)
Projects
None yet
Development

No branches or pull requests

4 participants