type — Intermediate Examples
Declares a type alias (3.12+)
Generic type aliases
Creating parameterized type aliases.
python
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}")
Type aliases give readable names to complex types. They're especially useful for callbacks (Callable), nested generics, and domain-specific types.
type() for dynamic class creation
Using type() as a class factory.
python
# type(name, bases, dict) creates a new class Dog = type("Dog", (), { "__init__": lambda self, name: setattr(self, "name", name), "bark": lambda self: f"{self.name} says Woof!", "species": "Canis familiaris", }) d = Dog("Rex") print(d.bark()) print(f"Species: {d.species}") print(f"Type: {type(d)}") # Dynamic class with inheritance Animal = type("Animal", (), { "breathe": lambda self: "breathing..." }) Cat = type("Cat", (Animal,), { "__init__": lambda self, name: setattr(self, "name", name), "meow": lambda self: f"{self.name} says Meow!", }) c = Cat("Whiskers") print(c.meow()) print(c.breathe()) print(f"Is Animal: {isinstance(c, Animal)}")
Expected Output
Rex says Woof! Species: Canis familiaris Type: <class '__main__.Dog'> Whiskers says Meow! breathing... Is Animal: True
type() with three arguments creates a class dynamically. This is what Python does behind the scenes for every class statement.
Want to try these examples interactively?
Open Intermediate Playground