Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiline lambda

Tags:

python

c#

lambda

I am wondering if there is possible to find some equivalent to C# multiline lambda function in Python.

Let's say, that I have C# code like this: enter image description here

I want to write some equivalent python code for this method. But as far as I know there is no possibility to have multiline lambda functions in python. Any ideas about some python equivalent code for this?

like image 826
Bill Avatar asked Mar 22 '17 13:03

Bill


1 Answers

You can define your lambda on multiple lines if you put the expression in parentheses. This creates an implied line continuation, causing newlines to be ignored up to the closing parenthesis.

>>> func = lambda a,b: (
...     b - a if a <= b else
...     a*b
... )
>>>
>>> func(23, 42)
19

You can also explicitly use the line continuation character "\", but this is not the approach preferred by the Python style guide. (Not that binding lambdas to names are a good idea to begin with, in fairness...)

>>> func = lambda a,b: \
...     b - a if a <= b else \
...     a*b
>>>
>>> func(23, 42)
19

Of course, you can only have expressions inside your lambda, and not statements. So proper if blocks and returns and the like are still impossible.


Additionally, it may not be necessary to use lambdas here at all, because unlike C# (prior to the recent v. 7.0), Python is capable of nesting full functions:

>>> def method(x,y):
...     def func(a,b):
...             if a <= b:
...                     return b - a
...             return a * b
...     return func(x,y)
...
>>> method(23, 42)
19
like image 190
Kevin Avatar answered Oct 24 '22 14:10

Kevin