Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify argument type in lambda? [duplicate]

Tags:

python

lambda

For usual functions, you can annotate the type as follows

def my_function(arg1: int)

How do I do this in lambda?

lambda a: int, b: int : a+b

gives a syntax error.

like image 647
Rufus Avatar asked Dec 06 '16 07:12

Rufus


People also ask

Can lambda take multiple arguments?

A lambda function can have as many arguments as you need to use, but the body must be one single expression.

How do you write multiple statements in lambda expression?

Lambda functions does not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function.

Can lambda take two arguments Python?

Just like a normal function, a Lambda function can have multiple arguments with one expression. In Python, lambda expressions (or lambda forms) are utilized to construct anonymous functions. To do so, you will use the lambda keyword (just as you use def to define normal functions).


2 Answers

The question was: "How to specify argument type in python lambda?". Although the other answers are good, they do not provide answer to this main question.

The answer is: you cannot.

From the PEP specification of function annotations:

lambda 's syntax does not support annotations. The syntax of lambda could be changed to support annotations, by requiring parentheses around the parameter list. However it was decided [12] not to make this change because:

It would be an incompatible change. Lambda's are neutered anyway. The lambda can always be changed to a function.

For reference: https://stackoverflow.com/a/33833896/7051394

like image 155
Right leg Avatar answered Oct 09 '22 07:10

Right leg


The problem is that reduce will compute

result1 = func(x1, x2)
result2 = func(result1, x3)
...

your function accepts two lists and returns a number, so on the second call the function fails (unless you only provide two elements).

To be able to use reduce the function should accept two arguments and return a value of the same type of the arguments because the output of the function will be re-used as input at next iteration.

like image 36
6502 Avatar answered Oct 09 '22 07:10

6502