Careeroza
Python Type Hints
Type Hints Drive FastAPI
Example
Type hints declare what type a value should be. Python itself does not enforce them, but FastAPI and Pydantic read them to validate and convert data:
def greet(name: str, times: int = 1) -> str:
return " ".join([f"Hello {name}!"] * times)
print(greet("Asha", 2))
print(greet.__annotations__)Output
Hello Asha! Hello Asha!
{'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}Common Types
Example
from datetime import date
from typing import Literal
tags: list[str] = ["python", "api"]
scores: dict[str, int] = {"asha": 92}
nickname: str | None = None # optional value
level: Literal["basic", "advance"] = "basic"
joined: date = date(2024, 6, 1)
print(tags, scores, nickname, level, joined.isoformat())Output
['python', 'api'] {'asha': 92} None basic 2024-06-01