'Is it possible to type hint a lambda function?

Currently, in Python, a function's parameters and return types can be type hinted as follows:

def func(var1: str, var2: str) -> int:
    return var1.index(var2)

Which indicates that the function takes two strings, and returns an integer.

However, this syntax is highly confusing with lambdas, which look like:

func = lambda var1, var2: var1.index(var2)

I've tried putting in type hints on both parameters and return types, and I can't figure out a way that doesn't cause a syntax error.

Is it possible to type hint a lambda function? If not, are there plans for type hinting lambdas, or any reason (besides the obvious syntax conflict) why not?



Solution 1:[1]

Since Python 3.6, you can (see PEP 526):

from typing import Callable
is_even: Callable[[int], bool] = lambda x: (x % 2 == 0)

Solution 2:[2]

For those just looking for a swift access to intellisense when writing your code, an almost-hack is to type-annotate the parameter just before the lambda declaration, do your work and only then shadow it with the parameter.

    x: YourClass
    map(lambda _ :  x.somemethod ...) # x has access to methods defined on YourClass

Then, right after:

    x: YourClass # can remove or leave
    map(lambda x:  x.somemethod, ListOfYourObjects) # inner x now shadows the argument

Solution 3:[3]

this works fine for me...

def fun()->None:
    def lam(i: int)->None:
        print("lam!", i)
    print("fun!")
    lam(1)
    lam(2)


fun()
lam()

prints

fun!
lam! 1
lam! 2
Traceback (most recent call last):
  File "/home/jail/prog.py", line 16, in <module>
    lam()
NameError: name 'lam' is not defined

tested on CPython 3.6.12 and 3.10.2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 rtviii
Solution 3 hanshenrik