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?
Since Python 3.6, you can (see PEP 526):
As user c-z noted, this is not the same as annotating the signature of a non-anonymous function though. Mypy v0.620 doesn't complain if you pass a
str
variable tois_even
in the above example.You can, sort of, in Python 3.6 and up using PEP 526 variable annotations. You can annotate the variable you assign the
lambda
result to with thetyping.Callable
generic:This doesn't attach the type hinting information to the function object itself, only to the namespace you stored the object in, but this is usually all you need for type hinting purposes. Note that you can't annotate
*args
or**kwargs
arguments separately this way, as the documentation forCallable
states:For the
lambda
expression itself, you can't use any annotations (the syntax on which Python's type hinting is built). The syntax is only available fordef
function statements.From PEP 3107 - Function Annotations:
You can still attach the annotations directly to the object, the
function.__annotations__
attribute is a writable dictionary:Not that dynamic annotations like these are going to help you when you wanted to run a static analyser over your type hints, of course.