Introduction
Advanced type system features including generics, protocols, and type variables.
Generics
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self):
self._items: List[T] = []
def push(self, item: T):
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
Protocols
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None:
...
def render(obj: Drawable):
obj.draw()
class Circle:
def draw(self):
print("Drawing circle")
TypedDict
from typing import TypedDict
class User(TypedDict):
name: str
age: int
email: Optional[str]
def create_user(data: User) -> User:
return data
NewType and Cast
from typing import NewType, cast
UserId = NewType('UserId', int)
admin_id = UserId(1)
def process_id(uid: int) -> int:
return uid * 2
result = process_id(admin_id) # Works
Practice Problems
- Create generic repository class
- Define protocol for file-like objects
- Use TypedDict for API response
- Create union of literal types
- Use @overload for multiple signatures