[Python-Dev] PEP 572: Assignment Expressions
Steven D'Aprano
steve at pearwood.info
Sat Apr 21 21:13:09 EDT 2018
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.
--
Steve
More information about the Python-Dev
mailing list