8

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
wonton
  • 7,568
  • 9
  • 56
  • 93

2 Answers2

10

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
wonton
  • 7,568
  • 9
  • 56
  • 93
  • 3
    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`. – chepner Sep 07 '17 at 22:59
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)
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179