Walrus operator variable in list-comprehension leaks into global namespace

Walrus operator variable leaking is fine for global use, but even when the walrus operator variable in the list comprehensions also leaking to globals is acceptable?
Should we not report it as a bug for it

[(t:=(t[1], sum(t)) if i else (0,1))[0] for i in range(20)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
t
(4181, 6765)

In the above example the t variable is leaking into the global-namespace
Even when in the list-comprehension. Is the design of walrus operator is such that it can be accessible in the global-namespace or should the implementation with list-comprehensions should change such that the variable does not leaks in globals namespace should we open an issue for this

2 Likes

From PEP572 Assignment Expressions:

A list comprehension can map and filter efficiently by capturing the condition:

results = [(x, y, x/y) for x in input_data if (y := f(x)) > 0]

Similarly, a subexpression can be reused within the main expression, by giving it a name on first use:

stuff = [[y := f(x), x/y] for x in range(5)]

Note that in both cases the variable y is bound in the containing scope (i.e. at the same level as results or stuff).

So this is exactly the result mandated by the PEP. Note the sentence “containing scope”, which is different from the global scope.

3 Likes

I am agree with @harshag .

If this is a FEATURE but not a BUG, I think this is a bad feature.

In your example:

>>> arr = [[y := x + 1, x / y] for x in range(5)]

The Y will be exposed in globol, but X is not.It will be confusing.

I remember that the X in list comprehensions was also exposed in globol in older Python version, but it is fixed now.

The local parameters in the list comprehensions will not be exposed in global, and will not change the parameters defined before.