Python Type Hints

Type hints allow you to describe the expected types of variables, function parameters, and return values. They improve readability and help development tools detect type-related mistakes.

Type Hints for Variables

Python
Add types to variables.
name: str = "Alice"
age: int = 25
price: float = 99.99
active: bool = True

Function Type Hints

Python
Specify parameter and return types.
def add(a: int, b: int) -> int:
    return a + b

print(add(10, 20))

Type Hints for Collections

Python
Type a list and dictionary.
names: list[str] = ["Alice", "Bob"]
users: dict[str, int] = {
    "Alice": 25,
    "Bob": 30
}

Optional Values

Use a union type when a value can have more than one possible type, such as a string or None.

Python
A function that may return None.
def find_name(user_id: int) -> str | None:
    if user_id == 1:
        return "Alice"
    return None

Type Hints with Classes

Python
Use a class as a type.
class User:
    def __init__(self, name: str):
        self.name = name


def greet(user: User) -> str:
    return f"Hello {user.name}"

Benefits of Type Hints

Type hints improve code readability, provide better editor support, make large projects easier to maintain, and allow static type checkers to find potential problems.

Summary

Python type hints document the expected types of data without changing Python's dynamic nature. They are especially useful for functions, collections, classes, and larger codebases.