[New-bugs-announce] [issue35877] parenthesis is mandatory for named expressions in while statement

Karthikeyan Singaravelan report at bugs.python.org
Fri Feb 1 05:55:55 EST 2019


New submission from Karthikeyan Singaravelan <tir.karthi at gmail.com>:

I thought to open a separate report itself in order to keep the original issue not cluttered with questions since it could be used for other docs. Sorry for my report there. Original report as per msg334341 .

It seems parens are mandatory while using named expressions in while statement which makes some of the examples invalid like https://www.python.org/dev/peps/pep-0572/#sysconfig-py . From my limited knowledge while statement Grammar was not modified at https://github.com/python/cpython/pull/10497/files#diff-cb0b9d6312c0d67f6d4aa1966766ceddR73 and no tests for while statement which made me assume it's intentional. I haven't followed the full discussion about PEP 572 so feel free to correct me if it's a conscious decision and in that case the PEP 572 can be updated.

# python info

➜  cpython git:(master) ./python.exe
Python 3.8.0a0 (heads/bpo35113-dirty:49329a217e, Jan 25 2019, 09:57:53)
[Clang 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

# Example as in PEP 572 to create a simple file that reads itself and prints lines that matches "foo"

➜  cpython git:(master) cat /tmp/foo.py
import re

with open("/tmp/foo.py") as f:
    while line := f.readline():
        if match := re.search(r"foo", line):
            print(match.string.strip("\n"))
➜  cpython git:(master) ./python.exe /tmp/foo.py
  File "/tmp/foo.py", line 4
    while line := f.readline():
               ^
SyntaxError: invalid syntax

# Wrapping named expression with parens for while makes this valid

➜  cpython git:(master) cat /tmp/foo.py
import re

with open("/tmp/foo.py") as f:
    while (line := f.readline()):
        if match := re.search(r"foo", line):
            print(match.string.strip("\n"))
➜  cpython git:(master) ./python.exe /tmp/foo.py
with open("/tmp/foo.py") as f:
        if match := re.search(r"foo", line):


As a user I think parens shouldn't be mandatory in while statement since if statement works fine. Parens can cause while statement to be superfluous in some cases and an extra case to remember while teaching.

----------
components: Interpreter Core
messages: 334665
nosy: emilyemorehouse, gvanrossum, xtreak
priority: normal
severity: normal
status: open
title: parenthesis is mandatory for named expressions in while statement
type: behavior
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue35877>
_______________________________________


More information about the New-bugs-announce mailing list