[ Web Proxy ]
URL:
Viewing: https://www.pythonbyexample.dev/examples/type-hints [Back]  [Original]

Type Hints Python By Example Skip to main content Python By ExampleJourneysAbout
All examplesPython docs reference

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

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

Virtual EnvironmentsRuntime Type Checks

Run the complete 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.

adewale/pythonbyexample Python 3.13 docs Privacy
Web Proxy Viewer  |  New URL  |  Original Page