Skip to content

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

Closed
@dhood

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions