Re: [Python-Dev] PEP 572: Assignment Expressions

2018年4月21日 11:05:34 -0700

[Matthew Woodcraft <[email protected]>]
> I would like to suggest one more motivating example for "Capturing
> condition values": multiple regex matches with 'elif'.
>
> if match := re.search(pat1, text):
> print("Found one:", match.group(0))
> elif match := re.search(pat2, text):
> print("Found two:", match.group(0))
> elif match := re.search(pat3, text):
> print("Found three:", match.group(0))
>
> Without assignment expressions, you have an annoying choice between a
> cascade of 'else's with an ever-increasing indent and evaluating all the
> matches up front (so doing unnecessary work).
That's a reasonable use, but would more likely be written like so today:
for tag, pat in (("one", pat1), ("two", pat2), ("three", pat3).
("four", pat4), ...):
 match = re.search(pat, text)
 if match:
 print("Found", tag + ":", match.group(0))
 break
Which would still read a bit nicer if the first two loop body lines
could be collapsed to
 if match := re.search(pat, text):
_______________________________________________
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to