Python Type Checking with MyPy
Static type checking for Python code.
Catch type errors early.
Install MyPy
```bash pip install mypy ```
Basic Type Checking
```python # code.py def greet(name: str) -> str: return f"Hello {name}!"
def add(a: int, b: int) -> int: return a + b
This will fail type check result = add("5", "3")
Run: mypy code.py ```
Optional Types
```python from typing import Optional
def find_user(user_id: int) -> Optional[str]: if user_id == 1: return "Tom" return None
user = find_user(1) if user is not None: print(user.upper()) ```
Collection Types
```python from typing import List, Dict, Tuple, Set
def process_names(names: List[str]) -> Dict[str, int]: return {name: len(name) for name in names}
def get_coordinates() -> Tuple[float, float]: return (40.7128, -74.0060)
def unique_numbers(nums: List[int]) -> Set[int]: return set(nums) ```
Generics
```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()
stack = Stack[int]() stack.push(1) stack.push(2) ```
Protocol
```python from typing import Protocol
class Drawable(Protocol): def draw(self) -> None: ...
class Circle: def draw(self) -> None: print("Drawing circle")
def render(obj: Drawable) -> None: obj.draw()
circle = Circle() render(circle) # OK ```
MyPy Configuration
```ini # mypy.ini [mypy] python_version = 3.11 warn_return_any = True warn_unused_configs = True disallow_untyped_defs = True ```
Remember
- Run mypy before committing - Type hints improve code clarity - Optional makes None explicit