pythonpython-2.7python-typing

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

Solution

  • 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