Types

Type Hints

Annotations document expected types and power static analysis.

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
def f(x: int, y: str) -> bool: …
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

TypeAlias names a type so it can be reused with intent. Score: TypeAlias = int keeps the underlying type at runtime but lets the API talk about a domain concept rather than a primitive.

Source

from typing import TypeAlias

Score: TypeAlias = 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.