Type annotations in Python
Annotating parameters and returns with modern types.
def mean(values: list[float]) -> float:
return sum(values) / len(values)
def find(items: dict[str, int], key: str) -> int | None:
return items.get(key)
def label(value: int, unit: str = "ms") -> str:
return f"{value}{unit}"
Grid = list[list[int]]
def total(grid: Grid) -> int:
return sum(sum(row) for row in grid)
How it works
list[float]anddict[str, int]type collections.int | Nonemarks an optional return.- A type alias like
Gridnames a reusable shape.
Keywords and builtins used here
defdictfindfloatforintlabellenlistmeanreturnstrsumtotal
The run, in numbers
- Lines
- 17
- Characters to type
- 321
- Tokens
- 114
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 68 seconds.
Step 1 of 4 in Typing & dataclasses, step 20 of 53 in Pythonic Python.