Type of lambda function as function argument

I have a function that accepts 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 type a lambda function command.

I 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 like

def my_function(some_lambda: lambda) -> None:
  # type: (lambda) -> None
# formal parameter name expected
+4
source share
1 answer

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

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

Python version 2:

from typing import Callable
def my_function(some_lambda):
  # type: (Callable) -> None
+5
source

Source: https://habr.com/ru/post/1685263/


All Articles