Skip to content

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

Closed

Description

@dhood

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

Activity

  1. Akuli commented on Oct 25, 2021

    @Akuli
    Contributor

    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
    
  2. emmatyping commented on Oct 25, 2021

    @emmatyping
    Member

    Confirmed as fixed in master.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions