classification
Title: Walrus operator in list comprehensions [Python 3.8.0]
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Anselm Kiefner, EGN, eric.smith, steven.daprano, xtreak
Priority: normal Keywords:

Created on 2019-10-22 12:39 by EGN, last changed 2020-07-11 16:27 by Anselm Kiefner. This issue is now closed.

Messages (8)
msg355124 - (view) Author: (EGN) Date: 2019-10-22 12:39
Just tried to use Walrus operator in list comprehensions (for loop) and it is not possible.

Is it a bug?
msg355125 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2019-10-22 12:52
Can you please post a short snippet of what you are trying to do and the issue you are facing like traceback if any?
msg355126 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2019-10-22 13:03
We're not mind-readers, how do you expect us to know what you tried if you don't tell us?

The walrus operator works for me:

    >>> [spam for c in "hello world" if (spam:=c.upper()) in 'AEIOU']
    ['E', 'O', 'O']

    >>> [(spam:=x**2, spam+1) for x in range(5)]
    [(0, 1), (1, 2), (4, 5), (9, 10), (16, 17)]


What did you try, and what happened?
msg355128 - (view) Author: (EGN) Date: 2019-10-22 14:07
from os import getcwd, listdir, rename
import re

[rename(f'{p}{n}', f"{p}{''.join([w[:3] if len(w) > 3 else w for w in re.split('[-_. ]', n)[:-1]])}.{n.split('.')[-1]}")
 for n in listdir(p := f"{getcwd()}\\{input('Folder: ')}\\")]

When I run this code, I'm getting:
  File "C:\Users\1\Desktop\sn.py", line 4
    [rename(f'{p}{n}',f"{p}{''.join([w[:3] if len(w)>3 else w for w in re.split('[-_. ]',n)[:-1]])}.{n.split('.')[-1]}") for n in listdir(p:=f"{getcwd()}\\{input('Folder: ')}\\")]
                                                                                                                                         ^
SyntaxError: assignment expression cannot be used in a comprehension iterable expression

Process finished with exit code 1
msg355129 - (view) Author: (EGN) Date: 2019-10-22 14:11
But if I'm taking main for loop out of the square brackets everything works fine.

from os import getcwd, listdir, rename
import re

for n in listdir(p := f"{getcwd()}\\{input('Folder: ')}\\"):
    [rename(f'{p}{n}', f"{p}{''.join([w[:3] if len(w) > 3 else w for w in re.split('[-_. ]', n)[:-1]])}.{n.split('.')[-1]}")]
msg355130 - (view) Author: (EGN) Date: 2019-10-22 14:27
Even the simple code like this doesn't work:

[print(p) for n in (p := ['a', 'b', 'c'])]
msg355140 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2019-10-22 15:46
This is explicitly mentioned in PEP 572 as being disallowed:

"Due to design constraints in the reference implementation (the symbol table analyser cannot easily detect when names are re-used between the leftmost comprehension iterable expression and the rest of the comprehension), named expressions are disallowed entirely as part of comprehension iterable expressions (the part after each "in", and before any subsequent "if" or "for" keyword):"

The error message also makes it clear.
msg373527 - (view) Author: Anselm Kiefner (Anselm Kiefner) Date: 2020-07-11 16:27
I just stumbled over this same restriction and when I googled for "SyntaxError: cannot assign to named expression", 0 actual results showed - an absolute unicorn for a Python error.

> "Due to design constraints in the reference implementation (the symbol table analyser cannot easily detect when names are re-used between the leftmost comprehension iterable expression and the rest of the comprehension), named expressions are disallowed entirely as part of comprehension iterable expressions (the part after each "in", and before any subsequent "if" or "for" keyword):"

Might the new PEG parser maybe help alleviate this restriction, so we could declare this a bug instead?
History
Date User Action Args
2020-07-11 16:27:11Anselm Kiefnersetnosy: + Anselm Kiefner
messages: + msg373527
2019-10-22 15:46:02eric.smithsetstatus: open -> closed

nosy: + eric.smith
messages: + msg355140

resolution: not a bug
stage: resolved
2019-10-22 14:27:09EGNsetmessages: + msg355130
2019-10-22 14:11:34EGNsetmessages: + msg355129
2019-10-22 14:07:20EGNsetmessages: + msg355128
2019-10-22 13:05:04steven.dapranosettype: enhancement -> behavior
components: + Interpreter Core
2019-10-22 13:03:41steven.dapranosetnosy: + steven.daprano
messages: + msg355126
2019-10-22 12:52:58xtreaksetnosy: + xtreak
messages: + msg355125
2019-10-22 12:40:54EGNsettitle: Walrus operator in Python 3.8.0 in list comprehensions -> Walrus operator in list comprehensions [Python 3.8.0]
2019-10-22 12:39:25EGNcreate