[Python-Dev] PEP 572: Usage of assignment expressions in C

Tim Peters tim.peters at gmail.com
Tue May 1 00:06:07 EDT 2018


[Raymond Hettinger <raymond.hettinger at gmail.com>]
> Thanks Antoine, this is an important point that I hope doesn't get lost.
> In a language with exceptions, assignment expressions are less needful.
> Also, the pattern of having of having mutating methods return None
> further limits the utility.

It doesn't diminish the utility one whit in cases where binding
expressions are helpful ;-)

What you're saying is that there are _fewer_ such opportunities in
Python than in C.  Which may or may not be true (depending on the code
you're working with).  If you believe it is true, fine, then that also
argues against that people will rush to abuse the feature (to the
extent that it's even plausibly useful less often, to that extent also
will there be less temptation to use it at all).

But then I only care about use cases at heart, and have presented
real-life examples wherein binding expressions read both better and
worse than what they're replacing.  I intend to limit myself to the
cases where they read better :-)  Which are most of the cases I even
considered, BTW - in the vast majority of cases in real code I'd use
them, they'd be replacing the annoyingly bare-bones yet somehow
repetitive anyway:

    value = f()
    if value;
        doing something with value

with the still bare-bones but minimally repetitive:

    if value := f():
        doing something with value

For example, tons of functions I write and use return None or 0 or
False when they want to communicate "I have nothing useful to return
in this case - but since you expected that might happen, I'm not going
to annoy you with an exception".  That pattern isn't solely limited to
regexp search and match functions.

The "win" above is minor but frequent.  It adds up.

There are other cases where binding expressions really shine, but
they're much rarer in all the code I looked at (e.g., see the
uselessly ever-increasing indentation levels near the end of `copy()`
in the std library's copy.py).

In all, I expect I'd use them significantly more often than ternary
`if`, but far less often than augmented assignments.  If the PEP is
accepted, that's what all Pythoneers will be saying 5 years from now
;-)


More information about the Python-Dev mailing list