Add Python Type Hints to Legacy Code with Claude
Legacy Python code without type hints is hard to refactor safely and painful to navigate in an IDE. Paste a function or module and ask Claude to add proper type annotations — it infers types from usage patterns, docstrings, and naming conventions, and handles complex cases like Optional, Union, and generics correctly.
# Before — no type hints, hard to refactor safely
def process_orders(orders, discount_rate=None):
results = []
for order in orders:
total = order['amount'] * (1 - (discount_rate or 0))
results.append({'id': order['id'], 'total': total})
return results
Claude annotates it and suggests stronger types:
from typing import Optional, TypedDict
class Order(TypedDict):
id: int
amount: float
class OrderResult(TypedDict):
id: int
total: float
def process_orders(
orders: list[Order],
discount_rate: Optional[float] = None,
) -> list[OrderResult]:
results: list[OrderResult] = []
for order in orders:
total = order['amount'] * (1 - (discount_rate or 0))
results.append({'id': order['id'], 'total': total})
return results
Ask Claude to replace loosely typed dict structures with TypedDict or dataclasses — this gives you better IDE autocompletion and makes the code safe to refactor. You can also ask it to generate a mypy config alongside the annotated code.
Type hints aren't just documentation — they're the foundation for confident refactoring.
Log in to leave a comment.
The /security-review command scans your uncommitted changes for injection vectors, auth gaps, hardcoded secrets, and other common vulnerabilities.
The SessionStart hook fires when any session begins or resumes, making it ideal for loading environment variables and running one-time setup scripts.
Ask Claude to write property-based tests for your functions using fast-check — it identifies the mathematical invariants in your code and generates tests that cover inputs you'd never enumerate by hand.