Skip to content

Static Type Checking with Mypy

Why type checking

Type hints help you:

  • catch bugs before runtime
  • improve editor autocomplete
  • document function contracts

Minimal example

types_example.py
from typing import Iterable
 
 
def total(values: Iterable[int]) -> int:
    return sum(values)
types_example.py
from typing import Iterable
 
 
def total(values: Iterable[int]) -> int:
    return sum(values)

Running mypy

mypy your_package
mypy your_package

Example config (pyproject.toml)

[tool.mypy]
python_version = "3.11"
ignore_missing_imports = true
warn_unused_ignores = true
warn_redundant_casts = true
strict_optional = true
[tool.mypy]
python_version = "3.11"
ignore_missing_imports = true
warn_unused_ignores = true
warn_redundant_casts = true
strict_optional = true

Tip

Start with non-strict, then tighten gradually.

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did