Advanced Type Hints

Advanced PythonType SystemFree Lesson

Advertisement

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

  1. Create generic repository class
  2. Define protocol for file-like objects
  3. Use TypedDict for API response
  4. Create union of literal types
  5. Use @overload for multiple signatures

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement