[Python-ideas] Multi Statement Lambdas

Tobias Kohn kohnt at tobiaskohn.ch
Sun Oct 21 15:40:00 EDT 2018


  it might just be a detail, but Python does not even have  
single-statement lambdas.  The body of a lambda is an expression  
yielding a value, not a statement.

Function languages (from which the idea of the Lambda in Python  
probably came from) do not have statements at all.  Something like the  
example with "y = x+1; y*2" given earlier is usually expressed as a  
let-expression, which is syntactic sugar for a lambda itself.  Hence,  
the example could actually be written in Python like so (I am not  
saying it is beautiful, but just that it is possible ^_^):
  arr.map( lambda x: (lambda y:y*2)(x+1) )
Or, if you prefer (this seems to me to be syntactically very close to  
the original):
  arr.map( lambda x: (lambda y=x+1: y*2)() )

Moreover, in Python 3.8, we will have assignments in expressions, and  
(even though I obviously can't test this) I wonder if you could then  
write the same thing as:
  arr.map( lambda x: (y := x+1, y*2)[1] )

I guess, the original request is therefore not really about having  
multi-statement lambdas, but more about extending lambdas to anonymous  
functions with the possibility to have full statements inside the body.

Finally, I absolutely agree with that good naming is paramount for  
understandable code.  But IMHO, good naming means that I write a small  
/named/ function (describing its intent) if its body contains more  
than just a simple expression, anyway.

Cheers,
Tobias

Quoting Anders Hovmöller <boxed at killingar.net>:

>> A powerful general purpose language should not limit itself to one  
>> statement in a closure.
>
> Nitpick on language: It doesn't. Lambdas are not the only way to do  
> a closure.
>
> It's important to be precise when discussing these things.
>
>> Lets add mutli-statement lambdas to python either with just curly  
>> braces or with an indent based machine.
>
> Mostly it's just better with a function. Do you have some more  
> compelling examples where you can't use a function smoothly?
>
> / Anders
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideasCode of  
> Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20181021/7c73f844/attachment.html>


More information about the Python-ideas mailing list