[Python-Dev] PEP 572: intended scope of assignment expression

Victor Stinner vstinner at redhat.com
Thu Jul 5 08:20:01 EDT 2018


My work (*) in the "Assignment expression and coding style: the while
True case" thread helped me to understand something about the
*intended* scope.

While technically, assignment expressions keep the same scoping rules
than assignment statements, writing "if (x := func()): ..." or "while
(x := func()): ..." shows the "intented" scope of the variable. Even
if, as explained properly in the PEP, the scope is wider (for good
reasons) as "for line in file: ..." keeps line alive after the loop
(nothing new under the sun). It's something subtle that I missed at
the first read (of the code and the PEP), the difference is not

x = func()
if x:
    ... # obviously use x
# do we still plan to use x here?
# it's non obvious just by reading the if


if (x := func()):
    ... # obviously use x
# ":=" in the if "announces" that usually x is no longer used
# here, even if technically x is still defined

See my match/group PR for more concrete examples:

I understand the current PEP 572 rationale as: assignment expressions
reduces the number of lines and the indentation level... pure syntax

IMHO this "intended" scope is a much better way to sell assignment
expressions than the current rationale. In fact, it's explained later
very quickly in the PEP:

But it could be better explained than just "good effect in the header
of an if or while statement".

The PEP contains a good example of the intended scope:

if pid := os.fork():
    # Parent code
    # pid is valid and is only intended to be used in this scope
    ... # use pid
    # Child code
    # pid is "invalid" (equal to zero)
    ... # don't use pid
# since this code path is common to parent and child,
# the pid is considered invalid again here
# (since the child does also into this path)
... # don't use pid

(*) My work: my current 3 pull requests showing how assignment
expressions can be
used in the stdlib:

while True: https://github.com/python/cpython/pull/8095/files
match/group: https://github.com/python/cpython/pull/8097/files
list comp: https://github.com/python/cpython/pull/8098/files


More information about the Python-Dev mailing list