TypeVar
is a generic type variable that allows you to create a placeholder for a type. It is typically used when you want to define a generic function or class that can operate on different types without specifying them explicitly. It allows you to introduce a type variable that can be used as a type annotation for function arguments, return values, or class attributes.
Here's an example of how TypeVar can be used:
from typing import List, TypeVar
T = TypeVar('T')
def reverse_list(items: List[T]) -> List[T]:
return items[::-1]
names = ['Alice', 'Bob', 'Charlie']
reversed_names = reverse_list(names) # inferred as List[str]
numbers = [1, 2, 3, 4]
reversed_numbers = reverse_list(numbers) # inferred as List[int]
ParamSpec
is a special type introduced in Python 3.10 that allows you to specify generic parameter types for callable objects (functions, methods, etc.). It provides a way to indicate the expected types of arguments and return values for functions with variable parameter lists, such as variadic arguments or keyword arguments.
Here's an example of how ParamSpec can be used:
from typing import Callable, ParamSpec
P = ParamSpec('P')
def logger(func: Callable[P, None]) -> Callable[P, None]:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> None:
print("Calling function:", func.__name__)
result = func(*args, **kwargs)
print("Function called successfully!")
return result
return wrapper
@logger
def greet(name: str, age: int = 30) -> None:
print(f"Hello, {name}! You are {age} years old.")
greet("Alice", age=25)