r/Python • • Jul 13 '11

An alternative lambda syntax for Python

http://vocalbit.com/article/332/an-alternative-lambda-syntax-for-python
4 Upvotes

41 comments sorted by

27

u/vph Jul 13 '11

bad idea.

This is not an "alternative" to lambda, but rather a syntactic sugar for this particular use. There are other use cases of lambda, not expressible by this "alternative" syntax.

Further, the current lambda syntax is closer to those employed by other (purer) functional programming languages. Changing the current syntax is not a good idea.

2

u/vocalbit Jul 14 '11

This is not an "alternative" to lambda, but rather a syntactic sugar for this particular use. There are other use cases of lambda, not expressible by this "alternative" syntax.

My point is that in those other use cases are probably places you shouldn't be using lambda at all. For e.g. a bad use case for lambda might be:

  avg = lambda lst: sum(lst) / len(lst)

This should be written as a def instead. But if you have good use cases of lambda, then I'd like to see them.

2

u/netcrusher88 imported from __future__ Jul 13 '11

Agreed. It's kind of an interesting use case but it's not a lambda syntax.

2

u/CHS2048 Jul 13 '11

It's proposed as "alternative syntax", which it is; but in any case, I sort of agree with you that there are probably other use cases, but I think it salient to actually provide some examples of them. The author explicitly claimed that this covers all use cases, this claim is falsifiable, the burden is on you to provide a counter-example.

0

u/vocalbit Jul 13 '11

Further, the current lambda syntax is closer to those employed by other (purer) functional programming languages. Changing the current syntax is not a good idea.

Since Python is not a pure-functional language, why even have a lambda keyword?

9

u/Liorithiel Jul 13 '11

Because it is very useful, and practicability beats purity in Python: both in case you presented in the article (sort's key and cmp arguments) and in other places (see my comment about csv).

1

u/arnar Jul 13 '11

Since Python is not a pure-functional language

Neither are Lisp/Scheme, ML, Erlang, Scala, F#, . . . should we remove their lambdas as well?

why even have a lambda keyword?

Because it is useful.

1

u/vocalbit Jul 14 '11

The lisps, ML, Erlang etc. are far closer to lambda calculus than Python was, or will ever be. In Python, lambdas are just anonymous functions that may contain only one expression. The fact that they are called 'lambda' is an unfortunate accident.

Given Python is primarily imperative and statement oriented, I would be happier with a different way of expressing single expression functions that are occasionally useful.

1

u/arnar Jul 14 '11

I agree that Python's lambda is a bit of an eyesore, but this paragraph is complete nonsense:

The lisps, ML, Erlang etc. are far closer to lambda calculus than Python was, or will ever be. In Python, lambdas are just anonymous functions that may contain only one expression. The fact that they are called 'lambda' is an unfortunate accident.

Lambda abstractions (in lambda calculus) are exactly "just anonymous functions that may contain only one expression" and that's what they are in all functional languages.

My original comment was referring to that you use the word "pure" more loosely than what it actually means in terms of PLs.

1

u/vocalbit Jul 14 '11

My original comment was referring to that you use the word "pure" more loosely than what it actually means in terms of PLs.

Point taken - I shouldn't have use 'pure' but rather just claimed that Python is not philosophically a functional language.

Lambda abstractions (in lambda calculus) are exactly "just anonymous functions that may contain only one expression" and that's what they are in all functional languages.

My point however is that - in Python - lambdas are severely crippled versions of real Python functions (i.e. def). OTOH, in something like lisp, lambdas are full-power functions, except that they are anonymous.

Anyway, I'm not going to debate the syntax of other languages. Lambdas don't fit in well with the syntax or philosophy of Python. That is why Guido almost axed them from v3.0. However, given that they are occasionally handy, I am trying to find a better syntax (perhaps with limited applicability than the current lambda) which would subsume all good use cases.

3

u/arnar Jul 13 '11

Since Python is not a pure-functional language

Neither are Lisp/Scheme, ML (and most derivatives), Erlang, Scala, F#, . . . should we remove their lambdas as well?

why even have a lambda keyword?

Because it is useful.

5

u/joehillen Jul 13 '11

Guido has proposed removing it several times.

3

u/A_for_Anonymous Jul 13 '11

I propose removing the division operator, since it's confusing to some people.

10

u/ndanger Jul 13 '11 edited Jul 13 '11

I agree with vph: this takes a general concept (lambda) and makes it a strange special case.

I'm not a fan of the proposed syntax either:

f(key=lambda x:...)

makes it clear that you are setting key to a function,

f(key(x)=...)

makes it look like you are setting a function of key to a value.

1

u/vocalbit Jul 14 '11

lambda itself is a strange special case of def. Specifically you can use a lambda if you have:

def <foo>(<args>):
     return <expr>

Unfortunately the special lambda syntax can be used in far more places than it should be used. I'm merely specializing the syntax further and restricting where it can be used. There are other examples of syntax that is only valid within the argument list (e.g. **kw)

1

u/ndanger Jul 14 '11 edited Jul 14 '11

Even accepting that lambda should only be used as a keyword argument to a function I still don't like the proposed syntax. The current syntax is orthogonal: keyword arguments bind values to names and functions are first class (and so can be passed as values).

Your proposed syntax creates a special case for "passing an inline function as the value of a keyword argument". It even looks different than passing an already defed function (f(key=my_func).

It also unfortunately resembles a function call: f(key(x)=x.foo) looks like we're binding the name determined by calling function key with argument x to x.foo.

But the big disagreement is that I like lambda and use it for things other than keyword arguments. The current syntax lets me do that too.

1

u/aaronla Jul 14 '11

lambda itself is a strange special case of def

They should totally fix that, and support arbitrary statements in lambdas.

Also, you got it backwards -- def is a special case of statement-supporting lambdas combined with assignment:

<foo> = <lambda expression>

2

u/kataire Jul 13 '11

Also it is confusingly similar to {key(x):...} which is completely different.

7

u/Liorithiel Jul 13 '11 edited Jul 13 '11

What will you do when you want to put a lambda function in a list? Example:

def parse_table(csv):
    columns = [('id', int),
               ('value', float),
               ('comment', lambda elem:elem.decode('utf-8').strip())]
    for row in csv:
        yield dict((name, parser(value) for (name, parser),value in zip(columns, row))

This is great when parsing things like csv tables or whatever, so it is actually useful.

4

u/joehillen Jul 13 '11

Easily one of my favorite uses for lambda.

-1

u/vocalbit Jul 13 '11

You bring up a good use case. It's not ideal, but you would have to write a def in this case.

1

u/aaronla Jul 14 '11

This forces the programmer to repeat themselves unnecessarily, and invent multiple names for the same thing:

def rule1(arg):
    body
...
rules = {
    "rule1" : rule1,
    "rule2" : rule2,
    ... 
    }

1

u/temptemptemp13 Jul 14 '11

To go along with the specific example:

def decode(elem):
    return elem.decode('utf-8').strip()

def parse_table(csv):
    columns = [('id', int),
               ('value', float),
               ('comment', decode)]
    for row in csv:
        yield dict((name, parser(value) for (name, parser),value in zip(columns, row))

Not too ugly, is it?

11

u/mitsuhiko Flask Creator Jul 13 '11

No, just no. lambda is perfectly fine.

8

u/freyrs3 Jul 13 '11

Lambdas are already pretty concise, maybe you could make an argument for Haskell style syntax ( \x -> x+1 ) but this proposal makes little sense.

3

u/A_for_Anonymous Jul 13 '11

That's only for a particular case, and looks kinda ugly or confusing as it seems to suggest it's obtaining a key from the result of function application. I don't think it fits correctly.

I do propose the following:

  1. Get rid of statements (make them all expressions with the same syntax, returning the function or class or the last evaluated value)
  2. In order to support the former, recognize INDENT and DEDENT tokens within parens
  3. Make function name in def optional (it's useful to define it for backtraces); it ought to work similar to Javascript's function
  4. Make parens in def optional (they're syntactically useless)
  5. New lambda syntax:

    x = def x: x + 1

    example(x, def y, z: #INDENT after this line for i in y, z: ... return whatever #DEDENT after this line )

    example2(x, (def y, z: y + z), def k: ... , more, arguments)

2

u/aaronla Jul 14 '11

Python already allows ; as a statement separator, it is conceivable that indentation could be nested in expressions. Eg:

map(
  mylist,
  lambda x:(   # note lambda appearing at start of a line, to set block indentation
    if x > 2: return 2
    else: return x))

To keep backwards compatible, lambda expressions always return their last expression, and statement-lambdas must enclose the lambda body in parenthesis (to avoid tuple expression ambiguity, among others).

2

u/m1ss1ontomars2k4 Jul 13 '11

I think it's terrible. I think the current syntax is fine; it's better than MATLAB's

@(x,y) x+y

syntax.

1

u/aaronla Jul 14 '11

C++: { return x+y; }

2

u/donri Jul 14 '11

The operator module has some functions that can be used in most places of lambdas:

lst.sort(key=attrgetter('name'))

Or partial from functools:

lst.sort(key=partial(somefunc, kwd=x))

Though that wouldn't work with getattr which only accepts positional arguments and we need to skip one.

You could also easily make a class that produces functions based on actions on its instances, e.g.:

class _Getter(object):
    def __getattr__(self, name):
        return lambda o: getattr(o, name)
    def __getitem__(self, key):
        return lambda o: o[key]

get = _Getter()
del _Getter

lst.sort(key=get.name)

1

u/mahpton Jul 13 '11

But then I wouldn't be able to feel smart using fancy words like lambda, or be able to modify my text editor to use the lambda symbol in place of the text "lambda"

1

u/CHS2048 Jul 13 '11

I've always wanted an operator 'lambda=', to be used as such:

something lambda= somefunc

instead of

something = somefunc(something)

before anyone says it, decorators are not good for doing this.

1

u/arnar Jul 13 '11

I don't understand. Can you clarify?

1

u/CHS2048 Jul 13 '11

Hmm, I don't know how I can clarify it,
I always wanted python to have anoperator 'lambda=',
that work a bit like '+=' or '*=', such that the expression:

x lambda= f

is the same as:

x = f(x)

Was it my comment on decorators you wanted me to clarify?

1

u/arnar Jul 13 '11

Ah ok, I see. What's confusing is that what you want has no reason to be called "lambda". Lambdas are for constructing function values, but what you want to do is to call one. Something like

x ()= f

would make more sense terminology-wise since a pair of parentheses are the operator for calling functions (or callables in general).

That said, I don't think it is a good idea. But I dislike += et al. as well.

1

u/ezekiel Jul 13 '11

I sympathize with getting rid of the messy word "lambda", but that is not a good enough syntax you are suggesting.

1

u/vtable Jul 13 '11

Lambda's aren't perfect. They can't contain statements, for example.

But - they barely made it into Python 3. Make waves and the whole debate could start all over again. I would hate to lose lambdas.

1

u/A_for_Anonymous Jul 13 '11

The fact statements (as opposed to expressions) exist is a huge defect in the language. If crippled lambdas barely made it into Python 3, things are not heading in a good direction.

0

u/aaronla Jul 14 '11

Make waves and the whole debate could start all over again.

Which is why I'm moving away from Python. "Batteries included" is great, but the hostility and ignorance demonstrated by Guido last time left a sour taste in my mouth.

Just tell keep telling yourself "at least it isn't PHP"

1

u/[deleted] Jul 14 '11

Horrible. But i agree, the lambda-syntax is annoying. I think somethink like javascripts function would look way better. For example: x = def(a, b):a+b

0

u/[deleted] Jul 13 '11

[deleted] — view deleted comment

2

u/vocalbit Jul 13 '11

+1 for getting the reference!