Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typehinting lambda function as function argument

I have a function that takes in a lambda:

def my_function(some_lambda):
  # do stuff
  some_other_variable = some_lambda(some_variable)

my_function(lambda x: x + 2)

I would like to typehint the lambda function passed.

I've tried

def my_function(some_lambda: lambda) -> None:
# SyntaxError: invalid syntax
from typing import Lambda
# ImportError: cannot import name 'Lambda'

My IDE complains about similar things on 2.7 straddled typehints, eg

def my_function(some_lambda: lambda) -> None:
  # type: (lambda) -> None
# formal parameter name expected
like image 669
wonton Avatar asked Sep 07 '17 21:09

wonton


People also ask

How do you pass a lambda function as a parameter?

Passing Lambda Expressions as Arguments You can pass lambda expressions as arguments to a function. If you have to pass a lambda expression as a parameter, the parameter type should be able to hold it. If you pass an integer as an argument to a function, you must have an int or Integer parameter.

How do you define a lambda function with two arguments?

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).

Does lambda function support type annotation?

In particular, a lambda function has the following characteristics: It can only contain expressions and can't include statements in its body. It is written as a single line of execution. It does not support type annotations.

How do you type a lambda function?

The syntax of a lambda function is lambda args: expression . You first write the word lambda , then a single space, then a comma separated list of all the arguments, followed by a colon, and then the expression that is the body of the function.


1 Answers

This is obvious when you think about it, but it took a while to register in the head. A lambda is a function. There is no function type but there is a Callable type in the typing package. The solution to this problem is

from typing import Callable
def my_function(some_lambda: Callable) -> None:

Python 2 version:

from typing import Callable
def my_function(some_lambda):
  # type: (Callable) -> None
like image 105
wonton Avatar answered Oct 19 '22 21:10

wonton