PEP 572: Add additional motivation and examples

This commit is contained in:
Chris Angelico 2018-04-25 15:32:22 +10:00
parent 91f2de3928
commit 4d93701cce
1 changed files with 14 additions and 0 deletions

View File

@ -31,6 +31,14 @@ the worst of the confusions, we change the definition of comprehensions,
causing some edge cases to be interpreted differently, but maintaining the
existing behaviour in the majority of situations.
Additionally, naming sub-parts of a large expression can assist an interactive
debugger, providing useful display hooks and partial results. Without a way to
capture sub-expressions inline, this would require refactoring of the original
code; with assignment expressions, this merely requires the insertion of a few
``name :=`` markers. Removing the need to refactor reduces the likelihood that
the code be inadvertently changed as part of debugging (a common cause of
Heisenbugs), and is easier to dictate to a student or junior programmer.
Syntax and semantics
====================
@ -234,6 +242,12 @@ an ``if`` or ``while`` statement::
# of this effect
if match := re.search(pat, text):
print("Found:", match.group(0))
# The same syntax chains nicely into 'elif' statements, unlike the
# equivalent using assignment statements.
elif match := re.search(otherpat, text):
print("Alternate found:", match.group(0))
elif match := re.search(third, text):
print("Fallback found:", match.group(0))
# Reading socket data until an empty string is returned
while data := sock.read():