type — Intermediate Playground
Declares a type alias (3.12+)
Python Playground
from typing import TypeVar, Generic, TypeAlias
T = TypeVar("T")
# Type aliases with generics
Matrix: TypeAlias = list[list[float]]
Result: TypeAlias = tuple[bool, str]
def transpose(m: Matrix) -> Matrix:
return [list(row) for row in zip(*m)]
m = [[1, 2, 3], [4, 5, 6]]
print(f"Original: {m}")
print(f"Transposed: {transpose(m)}")
# Callable type alias
from typing import Callable
Predicate: TypeAlias = Callable[[int], bool]
def filter_with(data: list[int], pred: Predicate) -> list[int]:
return [x for x in data if pred(x)]
evens = filter_with([1,2,3,4,5], lambda x: x % 2 == 0)
print(f"Evens: {evens}")
# Type checking at runtime
print(f"\nMatrix is: {Matrix}")
print(f"Result is: {Result}")
Output
Click "Run" to execute your code
Type aliases give readable names to complex types. They're especially useful for callbacks (Callable), nested generics, and domain-specific types.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?