Types

Type Hints

Annotations document expected types and power static analysis.

Type hints are annotations that document expected shapes for values, parameters, and return results. They exist so tools and readers can understand API boundaries before the program runs.

Python stores many annotations but does not enforce most of them at runtime. Use type hints for communication and static analysis; use validation or exceptions when runtime checks are required.

The alternative to an annotation is prose, tests, or runtime validation. Good Python code often uses all three at important boundaries.

Type hints document expected parameter and return shapes. Python still runs the function normally at runtime.

Source

def total(numbers: list[int]) -> int:
    return sum(numbers)

print(total([1, 2, 3]))

Output

6
Annotations describe expected types for tools; the runtime accepts any object regardless.

Python stores annotations on the function object for tools and introspection. Type checkers use this information without changing the function call syntax.

Source

print(total.__annotations__)

Output

{'numbers': list[int], 'return': <class 'int'>}

Most hints are not runtime validation. This call passes a string where the hint says int; Python still calls the function because the body can format any value.

Source

def label(score: int) -> str:
    return f"score={score}"

print(label("high"))

Output

score=high

Use X | Y (PEP 604) to express "either type". str | None says the result is a string or absent. typing.Optional[X] is the older, still-supported spelling for the same idea — Optional[X] is equivalent to X | None.

Source

def find(name: str, options: list[str]) -> str | None:
    return name if name in options else None

print(find("Ada", ["Ada", "Grace"]))
print(find("Guido", ["Ada", "Grace"]))


from typing import Optional

def lookup(name: str) -> Optional[int]:
    table = {"Ada": 1815, "Grace": 1906}
    return table.get(name)

print(lookup("Ada"))
print(lookup("Guido"))

Output

Ada
None
1815
None

The type statement names a type so it can be reused with intent. type Score = int keeps the underlying type at runtime but lets the API talk about a domain concept rather than a primitive. Older code spells this Score: TypeAlias = int; typing.TypeAlias is deprecated since Python 3.12, and the type-aliases page covers the modern statement in depth.

Source

type Score = int

def grade(score: Score) -> str:
    return "pass" if score >= 50 else "fail"

print(grade(72))

Output

pass

Notes

See also

Run the complete example

Example code

Expected output

6
{'numbers': list[int], 'return': <class 'int'>}
score=high
Ada
None
1815
None
pass

Execution time appears here after you run the example.