[Python-ideas] Thoughts on lambda expressions

Chris Angelico rosuav at gmail.com
Wed Mar 2 19:17:28 EST 2016


On Thu, Mar 3, 2016 at 11:00 AM, Mike Miller <python-ideas at mgmiller.net> wrote:
> Hmm, can't think of a way to get rid of the colon without it looking like a
> generator, but perhaps we could tackle the other issues by letting "def"
> stand in for "lambda":
>
>         lambda x: x.y
>
>         def x: x.y
>
> It's shorter, not an esoteric word, and is analogous to a named function
> definition, reminiscent of javascript.  The lack of name/parens separates it
> from the standard form.  Doable, but of course its pretty late in the game
> to be changing lambda, perhaps in Python 4?

(Wow, I suck with the misclick. Or maybe this is a Zen koan - one
letter of response that represents a wealth of wisdom and insight. Or
not.)

Trouble with this is that there'd be two very similar-looking, but
syntactically disparate, constructs:

# Define a function called x that calls another function
# with itself as a parameter, and discards the return
# value, always returning None.
def x(): y(x)

# Define and then dispose of an anonymous function
# which takes a parameter and would return the
# result of calling y on that object.
def x: y(x)

One of them is a statement, the other an expression. I'm not sure if
the parser could handle that or not, but a lot of humans will have
trouble with it. The similarities between these constructs will mean
that a typo could easily flip the interpretation to the other,
resulting in a bizarre error message. Consider what happens when you
miss off a parenthesis:

def function1(name):
    print("Hello, %s!".format(name)

def function2(name):
    print("Goodbye, %s!".format(name))

Currently, the presence of the keyword 'def' inside an expression (the
not-yet-closed print call) is an immediate error. But if "def" can
introduce an anonymous function, the reported error might be a
complaint about parentheses, or it might be to do with having no
operator between the string method call and the function; depending on
the exact syntax being used, this could result in extremely confusing
errors.

Much simpler if statements and expressions have a bit more
distinction. And yes, I'm aware of the ternary conditional operator;
and I don't think it sets a good precedent here. Comprehensions and
genexps at least require bracketing, although they can run into the
same oddities:

print(x # oops, missed close bracket

for x in y: # hey, what's that colon doing there?

But I think this example is a smidge contrived.

ChrisA


More information about the Python-ideas mailing list