r/Python • u/vocalbit • Jul 13 '11
An alternative lambda syntax for Python
http://vocalbit.com/article/332/an-alternative-lambda-syntax-for-python10
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
lambdaitself is a strange special case ofdef. 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
lambdashould 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 functionkeywith argumentxtox.foo.But the big disagreement is that I like
lambdaand 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
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
-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
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:
Get rid of statements (make them all expressions with the same syntax, returning the function or class or the last evaluated value)
In order to support the former, recognize INDENT and DEDENT tokens within parens
Make function name in def optional (it's useful to define it for backtraces); it ought to work similar to Javascript's function
Make parens in def optional (they're syntactically useless)
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+ysyntax.
1
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 ()= fwould 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
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
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.