Types
Type Hints
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
6Python 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=highUse 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
NoneThe 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
passNotes
- Python does not enforce most type hints at runtime.
- Tools like type checkers and editors use annotations to catch mistakes earlier.
- Use
X | Yfor unions andOptional[X]for "X or None"; both spellings mean the same thing. - Reach for a
typealias when a domain name reads better than a raw primitive type. - Use runtime validation when untrusted input must be rejected while the program runs.
See also
- related: Union and Optional Types
- related: Type Aliases
- related: Generics and TypeVar
- related: Runtime Type Checks
Run the complete example
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.