Practical Type Hinting
Combining Lambda Functions with Type Hints
Basic Lambda Type Hinting
from typing import Callable
## Type-hinted lambda function
multiply: Callable[[int, int], int] = lambda x, y: x * y
result = multiply(5, 3)
print(result) ## Output: 15
Type Hinting Strategies for Lambda Functions
Simple Type Annotations
## Lambda with explicit type hints
process_number: Callable[[float], float] = lambda x: x * 2.5
print(process_number(4.0)) ## Output: 10.0
Complex Lambda Type Hints
from typing import List, Callable
## Lambda with list processing
filter_even: Callable[[List[int]], List[int]] = lambda nums: list(filter(lambda x: x % 2 == 0, nums))
numbers = [1, 2, 3, 4, 5, 6]
print(filter_even(numbers)) ## Output: [2, 4, 6]
Type Hinting Workflow
graph TD
A[Lambda Function] --> B{Type Annotation}
B --> C[Static Type Checking]
C --> D{Type Correct?}
D -->|Yes| E[Code Execution]
D -->|No| F[Type Error]
Advanced Type Hinting Techniques
Optional and Union Types
from typing import Optional, Union
## Lambda with optional and union types
safe_divide: Callable[[float, float], Optional[float]] = lambda x, y: x / y if y != 0 else None
## Union type lambda
process_value: Callable[[Union[int, str]], str] = lambda x: str(x).upper()
Common Patterns and Pitfalls
Pattern |
Description |
Best Practice |
Simple Transformation |
Single-line type conversion |
Use explicit type hints |
Complex Logic |
Multiple operations |
Consider named functions |
Error Handling |
Conditional processing |
Add type-safe checks |
from typing import Callable
import timeit
## Comparing typed and untyped lambda performance
typed_lambda: Callable[[int], int] = lambda x: x * 2
untyped_lambda = lambda x: x * 2
## Timing comparison
typed_time = timeit.timeit(lambda: typed_lambda(10), number=100000)
untyped_time = timeit.timeit(lambda: untyped_lambda(10), number=100000)
Best Practices for Lambda Type Hinting
- Use
Callable
for function type hints
- Specify input and output types
- Keep lambda functions simple
- Use type checkers like mypy
Real-world Example
from typing import List, Callable
def apply_transformation(
data: List[int],
transformer: Callable[[int], int]
) -> List[int]:
return list(map(transformer, data))
## Type-hinted lambda usage
squared: Callable[[int], int] = lambda x: x ** 2
numbers = [1, 2, 3, 4, 5]
result = apply_transformation(numbers, squared)
print(result) ## Output: [1, 4, 9, 16, 25]
At LabEx, we emphasize the importance of clear, type-hinted code for better maintainability and readability.