[Python-Dev] PEP 572: Assignment Expressions
Chris Angelico
rosuav at gmail.com
Mon Apr 30 11:30:37 EDT 2018
On Tue, May 1, 2018 at 12:30 AM, Mark Shannon <mark at hotpy.org> wrote:
> List comprehensions
> -------------------
> The PEP uses the term "simplifying" when it really means "shortening".
> One example is
> stuff = [[y := f(x), x/y] for x in range(5)]
> as a simplification of
> stuff = [(lambda y: [y,x/y])(f(x)) for x in range(5)]
Now try to craft the equivalent that captures the condition in an if:
results = [(x, y, x/y) for x in input_data if (y := f(x)) > 0]
Do that one with a lambda function.
> IMO, the "simplest" form of the above is the named helper function.
>
> def meaningful_name(x):
> t = f(x)
> return t, x/t
>
> [meaningful_name(i) for i in range(5)]
>
> Is longer, but much simpler to understand.
Okay, but what if there is no meaningful name? It's easy to say "pick
a meaningful name". It's much harder to come up with an actual name
that is sufficiently meaningful that a reader need not go look at the
definition of the function.
> I am also concerned that the ability to put assignments anywhere
> allows weirdnesses like these:
>
> try:
> ...
> except (x := Exception) as x:
> ...
>
> with (x: = open(...)) as x:
> ...
We've been over this argument plenty, and I'm not going to rehash it.
> def do_things(fire_missiles=False, plant_flowers=False): ...
> do_things(plant_flowers:=True) # whoops!
If you want your API to be keyword-only, make it keyword-only. If you
want a linter that recognizes unused variables, get a linter that
recognizes unused variables. Neither of these is the fault of the
proposed syntax; you could just as easily write this:
do_things(plant_flowers==True)
but we don't see myriad reports of people typing too many characters
and blaming the language.
ChrisA
More information about the Python-Dev
mailing list