[Python-Dev] PEP 572: Assignment Expressions

Chris Angelico rosuav at gmail.com
Fri Apr 20 02:52:06 EDT 2018


On Fri, Apr 20, 2018 at 4:32 PM, Robert Smallshire <rob at sixty-north.com> wrote:
> If you restrict the idea to 'if' and 'while', Why not render this using the
> existing 'as' form for binding names, already used with 'except' and 'with':
>
>     while learner.get(static_hint) as points:
>         learner.feed(f(points))
>
> The equivalent for 'if' helps with the regex matching case:
>
>     if re.match(r"...") as m:
>         print(m.group(1))
>
> I considered proposing these two forms in a PEP a few years ago, but never
> got around to it. To my eye, they fit syntactically into the language as-is,
> without introducing new symbols, operators or keywords, are consistent with
> existing usage, and address two relatively common causes of displeasing
> Python code.

And are limited to conditions that check the truthiness/falsiness of
the value you care about. So that works for re.match, but not for
anything that might return -1 (a lot of C APIs do that, so if you're
working with a thin wrapper, that might be all you get), and it'll
encourage people to use this form when "is not None" would be more
appropriate (setting up for a failure if ever the API returned a
falsey value), etc. It's similar if you use iter(func, None) - it's
actually doing an equality check, not an identity check, even though a
longhand form would be better written with "is not None".

Also, are you assuming that this is binding to a name, or can it
assign to other targets?

if re.match(...) as m[3]:
   ...

HINT: Saying "it should do whatever except and with do" won't answer
the question. Give it a try if you don't believe me. :)

ChrisA


More information about the Python-Dev mailing list