7  Typehint (Basic)

Source: https://fastapi.tiangolo.com/python-types/

7.1 Simple Types

def get_items(item_a: str, item_b: int, item_c: float, item_d: bool, item_e: bytes):
    return item_a, item_b, item_c, item_d, item_d, item_e

7.2 Generic Types

7.2.1 List

def process_items(items: list[str]):
    for item in items:
        print(item)

7.2.2 Tuple and Set

def process_items(items_t: tuple[int, int, str], items_s: set[bytes]):
    return items_t, items_s

7.2.3 Dict

def process_items(prices: dict[str, float]):
    for item_name, item_price in prices.items():
        print(item_name)
        print(item_price)

7.2.4 Union

# Python 3.10 (a lot better and simpler)
def process_item(item: int | str):
    print(item)
from typing import Union

def process_item(item: Union[int, str]):
    print(item)

7.2.5 Optional (possibly None)

Optional[Something] is actually a shortcut for Union[Something, None], they are equivalent.

from typing import Optional


def say_hi(name: Optional[str] = None):
    if name is not None:
        print(f"Hey {name}!")
    else:
        print("Hello World")

7.3 Classes as types

class Person:
    def __init__(self, name: str):
        self.name = name


def get_person_name(one_person: Person):
    return one_person.name

7.4 Pydantic Models

from datetime import datetime

from pydantic import BaseModel


class User(BaseModel):
    id: int
    name: str = "John Doe"
    signup_ts: datetime | None = None
    friends: list[int] = []


external_data = {
    "id": "123",
    "signup_ts": "2017-06-01 12:22",
    "friends": [1, "2", b"3"],
}
user = User(**external_data)
print(user)
# > User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3]
print(user.id)
# > 123
id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3]
123

7.5 Type Hints with Metadata Annotations

from typing import Annotated


def say_hello(name: Annotated[str, "this is just metadata"]) -> str:
    return f"Hello {name}"