Python Type Annotations
Type annotations describe the values a function expects and returns. A checker can use them to find a call that passes text where a read count belongs, before that call reaches your analysis.
This page builds on Functions. Use Python 3.13 to reproduce the examples. The annotation syntax here requires Python 3.10 or later because it uses X | Y unions. The examples use the standard library; the separate checker is mypy 2.4.0.
Annotate parameters and return values
Section titled “Annotate parameters and return values”The colon in count: int describes an argument. The arrow in -> int describes the returned value. A default follows the annotation, as in factor: int = 2. These are type hints, not conversion instructions. Python’s function annotation documentation explains their syntax.
def scale_count(count: int, factor: int = 2) -> int: """Multiply a read count by a factor.
Args: count: Number of reads. factor: Integer multiplier. Defaults to two.
Returns: The scaled read count. """ return count * factor
read_count: int = 12scaled_count: int = scale_count(read_count)print(scaled_count)24The variable annotation read_count: int describes the intended type of that name. It does not convert an assigned string to an integer. Mypy can infer int from read_count = 12, so you need not annotate every obvious assignment. Explicit annotations help at function boundaries and with empty collections. Mypy’s inference documentation describes this distinction.
Describe collections and tuples
Section titled “Describe collections and tuples”Use list[int] for integer elements and dict[str, int] for string keys with integer values. A set[str] holds unique strings. A fixed tuple lists its positions separately, so tuple[int, float] contains an integer followed by a float. These are the built-in collection forms supported by mypy.
def summarize_counts(counts: list[int]) -> tuple[int, float]: """Calculate the total and mean of a nonempty list of read counts.
Args: counts: Read counts for one sample.
Returns: A pair containing the total and arithmetic mean.
Raises: ValueError: If counts is empty. """ if not counts: raise ValueError("counts must not be empty") total = sum(counts) return total, total / len(counts)
gene_counts: list[int] = [0, 15, 230, 0, 45, 120, 0, 78]counts_by_gene: dict[str, int] = {"TP53": 15, "BRCA1": 0}selected_genes: set[str] = {"TP53", "BRCA1"}summary: tuple[int, float] = summarize_counts(gene_counts)print(summary)print(counts_by_gene["TP53"])print(sorted(selected_genes))(488, 61.0)15['BRCA1', 'TP53']list[int] does not promise a nonempty list or nonnegative counts. The explicit if not counts check prevents division by zero. The annotation describes element types; the docstring explains the result and the empty-input rule.
Handle missing values with a union
Section titled “Handle missing values with a union”int | None allows either an integer or None. It does not mean the caller can omit an argument. A default value makes an argument optional to supply. In older code, Optional[int] means the same type as int | None. Python’s typing reference distinguishes these meanings.
def find_count( counts: dict[str, int], gene: str, fallback: int | None = None) -> int | None: """Look up a gene count with a fallback for an absent gene.
Args: counts: Read counts indexed by gene name. gene: Gene to find. fallback: Value returned when the gene is absent. Defaults to None.
Returns: The stored count, or the fallback when the gene is absent. """ return counts.get(gene, fallback)
for gene in ["BRCA1", "EGFR"]: count = find_count(counts_by_gene, gene) if count is None: print(f"{gene}: no measurement") else: print(f"{gene}: scaled count {scale_count(count)}")BRCA1: scaled count 0EGFR: no measurementAfter count is None, the other branch has an integer that scale_count can accept. Mypy follows this type narrowing. Test for None explicitly: a zero count is a measurement, and if not count would also match zero. See mypy’s optional type examples.
Convert and validate external values
Section titled “Convert and validate external values”A union can describe accepted input forms too. Here, str | int permits a count from a text field or an existing integer. The function converts the value and rejects negative counts. An annotation alone performs neither operation.
def parse_count(value: str | int) -> int: """Convert an integer or integer text to a nonnegative read count.
Args: value: An integer or text accepted by int.
Returns: A nonnegative read count.
Raises: ValueError: If the text is not an integer or the count is negative. """ count = int(value) if count < 0: raise ValueError("read counts must be nonnegative") return count
print(parse_count("12"))print(parse_count(8))for raw_value in ["-3", "unknown"]: try: parse_count(raw_value) except ValueError as error: print(f"Rejected {raw_value!r}: {error}")128Rejected '-3': read counts must be nonnegativeRejected 'unknown': invalid literal for int() with base 10: 'unknown'Both rejected values are strings, which the annotation allows. A static checker cannot infer their validity as read counts from str. The conversion and range check enforce those rules when the function runs. The try block catches the expected failures so the demonstration continues. Python documents conversion with int and exception handling separately from annotations.
Mark an operation that returns None
Section titled “Mark an operation that returns None”Use -> None when a function changes state or prints a message without producing a result for the caller. This function updates the supplied dictionary. Because it reaches the end without a return statement, Python returns None.
def record_count(counts: dict[str, int], gene: str, count: int) -> None: """Store a gene count in the caller's dictionary.
Args: counts: Dictionary to update in place. gene: Gene name to store. count: Read count to store. """ counts[gene] = count
record_count(counts_by_gene, "EGFR", parse_count("8"))print(counts_by_gene){'TP53': 15, 'BRCA1': 0, 'EGFR': 8}The annotation does not prevent mutation. The docstring states that the caller’s dictionary changes. Mypy’s description of None covers functions with no useful return value.
Name a record when its fields have different types
Section titled “Name a record when its fields have different types”A result with a sample name, total, and mean has a different type for each field. TypedDict gives that dictionary a named structure. It lets a checker detect a missing field or a string assigned to total, without changing how you access the dictionary. See the mypy TypedDict guide.
from typing import TypedDict
class CountSummary(TypedDict): """Describe a sample's read count summary.
Attributes: sample_id: Sample identifier. total: Sum of read counts. mean: Arithmetic mean of read counts. """
sample_id: str total: int mean: float
def summarize_sample(sample_id: str, counts: list[int]) -> CountSummary: """Attach a sample identifier to a count summary.
Args: sample_id: Sample identifier. counts: Nonempty list of read counts.
Returns: A dictionary with the sample identifier, total, and mean.
Raises: ValueError: If counts is empty. """ total, mean = summarize_counts(counts) return {"sample_id": sample_id, "total": total, "mean": mean}
sample_summary = summarize_sample("sample_01", gene_counts)print(sample_summary){'sample_id': 'sample_01', 'total': 488, 'mean': 61.0}At runtime this is an ordinary dictionary. TypedDict does not validate a dictionary loaded from a file. Use a custom type when its named fields help callers understand the result; a plain tuple[int, float] is enough for the earlier pair.
Find an error before the analysis runs
Section titled “Find an error before the analysis runs”Python does not automatically validate argument or return types against annotations. This deliberate mistake passes text to scale_count. Multiplication repeats the text instead of scaling the number, and Python raises no exception. Python’s typing documentation states this runtime limitation explicitly.
raw_count = "12"print(scale_count(raw_count))print(scale_count(parse_count(raw_count)))121224The first call is wrong for a read count. The second call converts and validates the text before multiplication.
Save the Python blocks in order in type_annotations.py. In a new example
directory, initialize a project and install the pinned checker with uv.
uv init --bare --python 3.13uv add --dev mypy==2.4.0uv run python type_annotations.pyRun the checker separately. It examines the source without executing the analysis. The --strict option enables additional checks, including a requirement for annotated function definitions. See mypy’s getting started guide and command options.
uv run mypy --strict --no-incremental type_annotations.pytype_annotations.py:163: error: Argument 1 to "scale_count" has incompatible type "str"; expected "int" [arg-type]Found 1 error in 1 file (checked 1 source file)The diagnostic identifies the string argument and the expected integer. Its
line number depends on the comments and blank lines in your saved file. The
command exits with status 1 because this demonstration deliberately contains
an error. Replace scale_count(raw_count) with
scale_count(parse_count(raw_count)) and run the checker again.
A successful check does not prove that counts are nonnegative, that sample identifiers are correct, or that an analysis is scientifically valid. Mypy also skips most checks inside unannotated functions by default; adding annotations makes more of the program available to the checker.
Keep the three responsibilities separate
Section titled “Keep the three responsibilities separate”| Mechanism | Responsibility in these examples |
|---|---|
| Type annotation | count: int lets mypy detect the string argument. |
| Docstring | The text explains read counts, defaults, mutation, and raised errors. |
| Runtime check | int(value) and the negative-count check reject invalid data during execution. |
Add tests for behavior that types cannot express, as shown in Testing & Assertions.
Describe an input stream
Section titled “Describe an input stream”Use Iterable[int] when a function consumes integer values without requiring indexing or another pass.
Use Iterator[int] when the function returns a stream that supports next() and can become exhausted.
Both types come from collections.abc in modern Python.
The iterator lesson implements these contracts and shows why an annotation cannot restore an exhausted stream.
Further reading
Section titled “Further reading”The typing reference defines unions, Optional, and TypedDict. See Python typing reference.