seeking deeper (language theory) reason behind Python design choice

Chris Angelico rosuav at gmail.com
Mon May 7 17:47:24 EDT 2018


On Tue, May 8, 2018 at 6:27 AM,  <all-lists at stefan-klinger.de> wrote:
> Hi,
>
> I was wondering (and have asked on StackOverflow [1] in a more
> elaborate way) whether there is a deeper reason to not allow
> assignments in lambda expressions.
>
> I'm not criticising, I'm asking in order to know ;-)
>
> The surface-reason is the distinction between assignments and
> statements, but why it was designed this way (with respect to lambda,
> not in general)?
>
> So far, no satisfying answer has come up, except for maybe to avoid a
> programmer accidentally typing `=` instead of `==`, which I find a bit
> unsatisfying as the only reason.

What exactly would be the scope of the assigned name? Let's say we
have a fairly typical use of a lambda function:

items.sort(key=lambda item: item.creation_date)

Now let's change that a bit. How would assignment fit into that?

def sort_func(item):
    date = parse_date(item.creation_date)
    return date.day_of_week, date.year, date.month, date.day
items.sort(key=sort_func)

Makes sense - now we're putting everything made on a Tuesday before
everything made on a Friday (I'm sure that's important to someone,
somewhere). So obviously any assignment should be local to the lambda
function, right?

What about this lambda function?

click_count = 0
b = Button(master, text="Click me", command=lambda: click_count += 1)
b.pack()

Equally obviously, this assignment belongs in the surrounding scope.
It can't be both, though. How should that be resolved?

If you want a way to do assignment as part of an expression, join the
discussions about PEP 572. Have fun; it's probably approaching a
thousand emails so far.

ChrisA



More information about the Python-list mailing list