Practical Lambda Examples
Real-world Lambda Type Annotation Scenarios
from typing import List, Callable
def transform_data(
data: List[int],
transformer: Callable[[int], float]
) -> List[float]:
return list(map(transformer, data))
## Lambda with type hints for data scaling
scale_data = lambda x: int -> float: x * 1.5
numbers = [1, 2, 3, 4, 5]
scaled_numbers = transform_data(numbers, scale_data)
Filtering and Validation
from typing import List, Callable, Optional
def filter_data(
items: List[int],
condition: Callable[[int], bool]
) -> List[int]:
return list(filter(condition, items))
## Lambda for even number filtering
is_even = lambda x: int -> bool: x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter_data(numbers, is_even)
Sorting with Custom Comparators
from typing import List, Tuple, Callable
def custom_sort(
data: List[Tuple[str, int]],
key_func: Callable[[Tuple[str, int]], int]
) -> List[Tuple[str, int]]:
return sorted(data, key=key_func)
## Lambda for sorting by second element
sort_by_age = lambda x: Tuple[str, int] -> int: x[1]
people = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
sorted_people = custom_sort(people, sort_by_age)
Lambda Type Annotation Patterns
Pattern |
Use Case |
Example |
Simple Transformation |
Data conversion |
lambda x: int -> float |
Filtering |
Condition checking |
lambda x: int -> bool |
Sorting Key |
Custom comparison |
lambda x: Tuple[str, int] -> int |
Validation |
Input verification |
lambda x: str -> bool |
Error Handling with Type Hints
from typing import Optional, Callable
def safe_divide(
a: float,
b: float,
error_handler: Optional[Callable[[Exception], float]] = None
) -> float:
try:
return a / b
except ZeroDivisionError as e:
if error_handler:
return error_handler(e)
raise
## Lambda error handler
default_error = lambda e: Exception -> float: 0.0
result = safe_divide(10, 0, default_error)
Lambda Composition
from typing import Callable, TypeVar
T = TypeVar('T')
U = TypeVar('U')
V = TypeVar('V')
def compose(
f: Callable[[U], V],
g: Callable[[T], U]
) -> Callable[[T], V]:
return lambda x: T -> V: f(g(x))
## Example of function composition
double = lambda x: int -> int: x * 2
increment = lambda x: int -> int: x + 1
double_then_increment = compose(increment, double)
Lambda Type Checking Flow
graph TD
A[Lambda Definition] --> B[Type Annotation]
B --> C{Type Checker}
C --> |Validate Types| D[Compile-time Check]
D --> E[Runtime Execution]
C --> |Type Mismatch| F[Raise Type Error]
Best Practices for Lambda Type Annotations
- Keep lambdas simple and focused
- Use clear and precise type hints
- Prefer named functions for complex logic
- Leverage type checkers like mypy
By applying these practical examples, developers can effectively use type hints with lambda functions in their LabEx Python projects, improving code quality and readability.