28  Type Checking (Pure)

If you want to perform type hints and data validation in pure Python (i.e., without relying on C extensions or external compiled components), there are several popular packages you can consider. Below are some packages that are both widely used and implemented in pure Python.

28.1 dataclasses

(Python 3.7+)

  • Type: Built-in module
  • Use Case: Type hinting, simple data modeling, and validation with dataclass decorators.
from dataclasses import dataclass

@dataclass
class User:
    name: str
    age: int

    def __post_init__(self):
        if not isinstance(self.name, str):
            raise TypeError(f"Expected name to be a str, got {type(self.name)}")
        if not (0 <= self.age <= 120):
            raise ValueError(f"Age must be between 0 and 120, got {self.age}")

# Usage
user = User(name="Alice", age=30)  # Valid

try:
    user = User(name="Alice", age=150)  # Raises ValueError
except ValueError as e:
    print(f"Error: {e}")
Error: Age must be between 0 and 120, got 150

28.1.1 Annotation

from typing import Annotated

@dataclass
class ValueRange:
    lo: int
    hi: int

T1 = Annotated[int, ValueRange(-10, 5)]
T2 = Annotated[T1, ValueRange(-20, 3)]
T2
typing.Annotated[int, ValueRange(lo=-10, hi=5), ValueRange(lo=-20, hi=3)]

28.2 TypedDict

(Python 3.8+) - Type: Built-in module (typing.TypedDict) - Use Case: Type hinting for dictionaries, lightweight validation.

from typing import TypedDict

class User(TypedDict):
    name: str
    age: int

# Usage
user: User = {"name": "Alice", "age": 30}  # Valid