Types
Type Hints
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
NoneTypeAlias 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
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
TypeAliaswhen 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.