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:
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?
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 return
s 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With