Can Python lambda functions contain type hints? If so, how?

Python interview question for Advanced practice.

Answer

Python's lambda syntax lambda args: expression does not support inline type annotations for arguments or return values (e.g., lambda x: int is invalid). However, you can use the typing module to annotate the variable the lambda is assigned to. For example: myfunc: Callable[[int], int] = lambda x: x + 1.

Explanation

While the lambda syntax itself doesn't support inline annotations (e.g., lambda x: int), you can type-hint the variable holding the lambda using Callable.

Related Questions