Type Hints for Lambda Functions in Python
For lambda functions, you can apply type hints to clarify input and output types.
This tutorial shows you how to apply type hints to lambda functions.
Syntax for lambda type hints
You can add type hints to lambda functions by wrapping them in a function or variable definition.
from typing import Callable greet: Callable[[str], str] = lambda name: f"Hello, {name}!" print(greet("Ahmed"))
Output:
Hello, Ahmed
The lambda function takes a str
and returns a str
. Type hints make this clear to anyone reading the code or using tools like linters.
Type Hinting Lambda Functions with Multiple Parameters
To type hint lambdas with multiple parameters, use Callable
with a list of parameter types and the return type.
from typing import Callable calculate_discount: Callable[[float, float], float] = lambda price, discount: price - (price * discount / 100) print(calculate_discount(100.0, 10.0))
Output:
90.0
The lambda function subtracts the discount from the price. Type hints show that both inputs are float
, and the output is also float
.
Specify the return type of a lambda function
Specify the return type when creating a lambda to clarify what the function produces.
from typing import Callable generate_id: Callable[[str, int], str] = lambda name, id_num: f"{name}_{id_num}" print(generate_id("Salma", 101))
Output:
Salma_101
The lambda function takes a str
and an int
and returns a str
. The type hints ensure this is explicit.
Using type hints for lambdas with lists or dictionaries
You can type hint lambdas handling complex data like lists or dictionaries using List
, Dict
, or custom types.
from typing import List, Callable double_values: Callable[[List[int]], List[int]] = lambda nums: [num * 2 for num in nums] print(double_values([1, 2, 3, 4]))
Output:
[2, 4, 6, 8]
The lambda function takes a list of integers as input and returns a list of doubled values.
from typing import Dict, Callable format_dict: Callable[[Dict[str, str]], str] = lambda data: ", ".join(f"{k}: {v}" for k, v in data.items()) print(format_dict({"name": "Kareem", "role": "Analyst"}))
Output:
name: Kareem, role: Analyst
The lambda function takes a dictionary with string keys and values and returns a formatted string.
Type hinting lambdas when used with map()
When using lambdas with functional programming tools, type hints clarify what the lambda expects and returns.
from typing import List names: List[str] = ["Omar", "Hana", "Laila"] uppercased_names = list(map(lambda name: name.upper(), names)) print(uppercased_names)
Output:
['OMAR', 'HANA', 'LAILA']
The lambda function converts names to uppercase. The type hints for List
clarify the input and output data types.
# Lambda with filter() from typing import List numbers: List[int] = [1, 2, 3, 4, 5] even_numbers = list(filter(lambda num: num % 2 == 0, numbers)) print(even_numbers)
Output:
[2, 4]
The lambda filters even numbers from the list. Type hints can help document this transformation.
# Lambda with reduce() from functools import reduce from typing import List numbers: List[int] = [1, 2, 3, 4] sum_of_numbers = reduce(lambda acc, num: acc + num, numbers) print(sum_of_numbers)
Output:
10
The lambda adds numbers in the list iteratively. Type hints can specify that the inputs and output are int
.
Limitations and Considerations
Unlike regular functions, lambda functions cannot have in-line type annotations for their parameters. For example, this is invalid:
# This will raise an error lambda x: int, y: int: x + y
Instead, use Callable
to define the lambda type outside the function:
from typing import Callable add_numbers: Callable[[int, int], int] = lambda x, y: x + y result = add_numbers(5, 10) print(result)
Output:
15
You cannot directly add type hints inside lambda functions. Use external type hinting with Callable
for clarity and compatibility with tools.
Regular functions are better suited if you need in-line type annotations or extensive documentation.
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.