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.
Set up Claude Code as an automated reviewer in your CI pipeline — on every pull request, it reads the diff, checks for bugs, security issues, missing tests, and convention violations, then posts its findings as a PR comment. Your human reviewers get a head start because the obvious issues are already flagged before they look.
Before deploying, tell Claude to read your project — migrations, environment variables, queue workers, scheduled tasks, caching, third-party integrations — and generate a deployment checklist that's specific to your app. Not a generic "did you run migrations?" list, but one that knows YOUR infrastructure and catches the things YOUR deploy can break.
Instead of writing a README from memory or copying a template, tell Claude to read your project and generate one that's actually accurate — real setup instructions from your config, real architecture from your directory structure, real API examples from your routes, and real prerequisites from your dependency files.