Skip to content
Streak:0Loading your progress…Sign in

Module 5 · Lesson 1 of 2

Type hints & Protocols

Gradual typing that feels like TypeScript — checked by tools, not at runtime. ~25 min

Lesson notes

Coming from TypeScript

TypeScript

type Result = { ok: true; value: number } | { ok: false; error: string };
interface Notifier { send(to: string, msg: string): Promise<void> }
function first<T>(xs: T[]): T | undefined { return xs[0]; }

Python

from typing import Protocol, TypedDict, Literal

class Ok(TypedDict):
    ok: Literal[True]
    value: int

class Notifier(Protocol):          # structural, like a TS interface
    async def send(self, to: str, msg: str) -> None: ...

def first[T](xs: list[T]) -> T | None:   # 3.12+ generics syntax
    return xs[0] if xs else None

Hints aren't enforced at runtime. Run mypy or pyright in CI — the equivalent of tsc --noEmit. Pydantic (next module) adds runtime validation.

Practice

  1. 1. Dependency injection with a Protocol

    medium25 XP

    Define a Clock Protocol with def now(self) -> float. Write class RateLimiter taking max_calls: int, per_seconds: float, and a clock: Clock. Its allow() -> bool returns True if fewer than max_calls calls were allowed in the last per_seconds (sliding window), recording the call when allowed. Then write a FakeClock with a settable t attribute for tests.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor

  2. 2. Are hints enforced?

    Quizeasy5 XP
    def f(x: int) -> int: return x * 2 — what does f("ab") do at runtime?