Part 1 · 1 chapters · ~8 min
The Type System and Type Hints
Dynamic and strong typing, duck typing, classes, dataclasses and slots, inheritance and the MRO, abstract base classes and Protocols, type hints with generics, TypedDict and Literal, mypy and pyright in strict mode, and Pydantic models.
3
Gradual typing
code
from dataclasses import dataclass
from typing import Protocol, Literal
from decimal import Decimal
@dataclass(frozen=True, slots=True)
class Money:
minor: int
currency: Literal["NGN", "USD", "KES"]
class Notifier(Protocol): # structural: any class with send() satisfies it
def send(self, to: str, message: str) -> None: ...
def alert(n: Notifier, to: str) -> None:
n.send(to, "Your transfer is pending")
# mypy --strict . or pyright: catch alert(42, "x") before it runs
from pydantic import BaseModel, Field
class TransferIn(BaseModel):
amount_kobo: int = Field(gt=0)
to: str
TransferIn.model_validate({"amount_kobo": -5, "to": "ac_1"}) # raises ValidationErrorGRADUAL TYPING IN PYTHON
hints are optional, checked by tools, and increasingly used at runtime
swipe the figure sideways, or tap expand for full screen
1/5
dynamic typing
Python checks types when operations run: "1" + 1 raises TypeError at run time, not before.
types checked at run timeerrors appear when the line runs