On Sat, Apr 21, 2018 at 6:13 PM, Steven D'Aprano <st...@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)
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
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