assert_type tells the type checker to verify a value has a specific type.
1from typing import assert_type23data = get_data() # type: Any45# Runtime: no-op (does nothing)6# Type checker: verifies type7assert_type(data, dict) # Warns if data is not dict89# With specific types10from typing import Union1112value: Union[int, str] = get_value()1314if isinstance(value, int):15 assert_type(value, int) # Type checker knows it's int16 print(value + 1) # OK1718# With Pydantic19from pydantic import BaseModel2021class User(BaseModel):22 name: str23 age: int2425data = parse_obj(User, {"name": "Alice", "age": 25})26assert_type(data, User) # Verifies parse_obj returns User2728# With FastAPI29from fastapi import FastAPI3031app = FastAPI()3233@app.get("/users/{user_id}")34async def get_user(user_id: int):35 user = await fetch_user(user_id)36 assert_type(user, User) # Verifies fetch_user returns User37 return user
Benefits: