9

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
1
  • This question is similar to: How can I specify the function type in my type hints?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 27, 2024 at 13:37

2 Answers 2

11

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
Sign up to request clarification or add additional context in comments.

2 Comments

You can also further restrict the function type: e.g., Callable[[int], int] is the type of a one-argument function that takes an int and returns an int.
There is a function type (types.FunctionType), but it's not something you usually want to use, because it's more of an implementation detail (specifically, it's the type of things defined by def statements and lambda expressions; other types exist for callable things like built-in functions, methods, etc.)
0

Callable is the answer to your question.

from typing import Callable


some_lambda: Callable[[int], int] = lambda x: x + 2


def my_function(func: Callable[[int], int]) -> None:
    # do some stuff
        

my_function(some_lambda)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.