[Python-Dev] PEP 572: Assignment Expressions
Steve Dower
steve.dower at python.org
Sun Apr 22 18:13:32 EDT 2018
This example makes me want “if expr as name:” (same semantics as ‘with’, and the name is always bound to the expression result regardless of truthiness), but doesn’t move me on assignment expressions.
Cheers,
Steve
Top-posted from my Windows phone
From: Guido van Rossum
Sent: Saturday, April 21, 2018 19:09
To: Steven D'Aprano
Cc: Python-Dev
Subject: Re: [Python-Dev] PEP 572: Assignment Expressions
On Sat, Apr 21, 2018 at 6:13 PM, Steven D'Aprano <steve at pearwood.info> wrote:
On Sat, Apr 21, 2018 at 08:35:51PM +0100, Matthew Woodcraft wrote:
> Well, that's a reason to make the example a bit more realistic, then.
>
> Say:
>
> if match := re.search(pat1, text):
> do_something_with(match.group(0))
> elif match := re.search(pat2, text):
> do_something_else_with(match.group(0), match.group(1))
> elif match := re.search(pat3, text):
> do_some_other_things_with(match.group(0))
> and_also_with(match.group(1), match.group(2))
I don't think that a bunch of generic "do_something_with" functions is
precisely "realistic".
If I saw something like that, I'd try very hard to find a way to
refactor it into code like this:
for handler in handlers:
if handler.match(text):
handler.process()
break
else:
# handle no-match case here
where the knowledge of what to search for, where to search for it, how
to search for it, and what to do when found, was encapsulated in the
handler objects. Your tastes may vary.
But your point is well-taken that the version with binding assignment
(thanks Tim!) is nicer to read than the current procedural version:
match = re.search(pat1, text)
if match:
do_something_with(match.group(0))
else:
match = re.search(pat2, text)
if match:
do_something_else_with(match.group(0), match.group(1))
else:
match = = re.search(pat3, text)
do_some_other_things_with(match.group(0))
and_also_with(match.group(1), match.group(2))
I just don't think it counts as a motivating use-case distinct from the
single match case.
The version of this code found in reality is not as regular as the example quoted, and the rebuttal "but I would rewrite it with a loop" shoots a straw man. To me the if-elif-elif portion of the example is very much a separate motivation, since being able to put the assignment in the elif clause avoids runaway indentation. I've regretted not being able to use elif in this kind of situation many times, whereas in the single match case I don't find it a burden to assign the variable in a separate statement preceding the if-clause. (I guess this is a case of "flat is better than nested" -- thanks Tim! :-)
--
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180422/a53b51e1/attachment.html>
More information about the Python-Dev
mailing list