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.1dataclasses
(Python 3.7+)
Type: Built-in module
Use Case: Type hinting, simple data modeling, and validation with dataclass decorators.
from dataclasses import dataclass@dataclassclass User: name: str age: intdef __post_init__(self):ifnotisinstance(self.name, str):raiseTypeError(f"Expected name to be a str, got {type(self.name)}")ifnot (0<=self.age <=120):raiseValueError(f"Age must be between 0 and 120, got {self.age}")# Usageuser = User(name="Alice", age=30) # Validtry: user = User(name="Alice", age=150) # Raises ValueErrorexceptValueErroras e:print(f"Error: {e}")
Error: Age must be between 0 and 120, got 150
28.1.1 Annotation
from typing import Annotated@dataclassclass ValueRange: lo: int hi: intT1 = Annotated[int, ValueRange(-10, 5)]T2 = Annotated[T1, ValueRange(-20, 3)]