Python24 min read
Python Type Checking with MyPy
Catch type mistakes before runtime using MyPy, make your code easier to understand, and reduce bugs in large codebases with static type checks.
David Miller
August 30, 2025
5.6k147
Python is dynamically typed, so many type errors appear only when code runs.
MyPy helps by checking types before execution.
This is especially helpful in:
- large projects
- team projects
- long-term maintainable code
## Install MyPy
```bash
pip install mypy
```
## Simple example (type error is caught early)
```python
def add(a: int, b: int) -> int:
return a + b
result = add("5", "3") # wrong types
```
Run:
```bash
mypy code.py
```
## Optional types (None handling)
```python
from typing import Optional
def find_user(user_id: int) -> Optional[str]:
if user_id == 1:
return "Tom"
return None
user = find_user(2)
if user is not None:
print(user.upper())
```
## Collections types
```python
from typing import List, Dict, Tuple, Set
names: List[str] = ["Tom", "Sarah"]
scores: Dict[str, int] = {"Tom": 90}
point: Tuple[int, int] = (10, 20)
unique: Set[int] = {1, 2, 3}
```
## Generics example (Stack)
```python
from typing import TypeVar, Generic, List
T = TypeVar("T")
class Stack(Generic[T]):
def __init__(self) -> None:
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
s = Stack[int]()
s.push(10)
```
## Graph: bug prevention
```mermaid
flowchart LR
A[Write code] --> B[Run mypy]
B --> C{Types OK?}
C -->|Yes| D[Run program safely]
C -->|No| E[Fix type errors early]
```
## Remember
- Type hints improve readability
- MyPy catches many bugs before runtime
- Best for medium/large codebases
#Python#Advanced#Type Checking