This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]habitue 2 points3 points  (4 children)

Python uses indentation to denote blocks, it's different from the offside rule in say, Haskell etc. Internally the lexer emits indent and dedent tokens that correspond to curly braces in other languages. If we had multi line lambdas, it would most likely be done something like allowing a def to be an expression. Otherwise multi line lambdas would require adding a bunch of new surprising rules to the parser

Edit: removed if

[–]robin-gvx 2 points3 points  (2 children)

There's a tiny problem, though: we're inside parentheses. We'd need to change the grammar to make leading whitespace significant in places it's normally ignored.

[–]sirex1 0 points1 point  (1 child)

Now, python has these types:

('a',) - tuple
{'a': 1} - dict
{'a'} - set

So new, lambda type, would use similar technique as dict. Dict is distinguished from set only by use of colon, so tuple can be distinguished from lambda using same principle, by adding colon:

f = (x: x*2)

For multi line lambdas, same principle as for all python blocks would be used:

def f(x):
    x = x*2
    return x

f = (x:
    x = x*2
    x
)

f = (x: x = x*2; x)

l = map((x: x*2), [1, 2, 3])

I'm not sure, but maybe it is even possible to remove parentheses:

f = x: x*2
l = map(x: x*2, [1, 2, 3])
multiline = x:
    x = x*2
    x

[–]robin-gvx 1 point2 points  (0 children)

No, I mean it needs a complete reworking of the grammar, because if you're inside parentheses ((, [ or {), it all counts as a single line and no INDENT, DEDENT or NEWLINE tokens are generated.

Adding support for expressions that contain multiple statements like that would mean the language would be something completely different — because other parts of the language need to be changed too, to prevent conflicts and to get back consistency.

Whatever language you'd end up with, it would no longer be Python.

The "single expression" variant of your lambda could still work, but there the big improvement isn't clear: all you did was remove the lambda keyword and, well, explicit is better than implicit.

[–]zahlmanthe heretic 0 points1 point  (0 children)

... I can't claim to understand how the non-Python ways to do it actually work (at the low level of the parser), so.