How to use Claude Code for Python development. Django, Flask, FastAPI, data science, automation scripts, and Python-specific tips.
Claude Code for Python Developers: Complete Guide
Python developers have unique needs. Django projects. Flask APIs. FastAPI services. Data science notebooks. Automation scripts.
Claude Code handles all of it. Here's how to use it effectively for Python development.
Why Python Developers Love Claude Code
- Full project understanding - Reads your entire codebase, not just the current file
- Framework awareness - Understands Django, Flask, FastAPI patterns
- Type hint support - Generates properly typed Python code
- Testing integration - Creates pytest tests that match your patterns
- Virtual environment aware - Respects your project's dependencies
Setup for Python Projects
Basic Setup
cd your-python-project
claude
Claude Code automatically detects Python projects from:
requirements.txt
pyproject.toml
setup.py
.py files
Recommended Project Structure
For best results, have:
your-project/
├── src/
│ └── your_package/
├── tests/
├── requirements.txt (or pyproject.toml)
├── README.md
└── .env.example
Claude Code understands standard Python project layouts.
Django Development
Creating Django Apps
> Create a new Django app called 'products' with:
- Product model (name, price, description, category)
- Admin registration with search and filters
- REST API endpoints using DRF
- Basic tests for the model and API
Claude Code will:
- Run
python manage.py startapp products
- Create the model with proper fields
- Register in admin with customization
- Create serializers and viewsets
- Add URL routing
- Write pytest/unittest tests
Django-Specific Prompts
> Add user authentication with:
- Custom user model (email as username)
- JWT tokens for API
- Login/logout/register views
- Password reset flow
> Optimize the queryset in ProductListView
to reduce database queries. We're seeing
N+1 problems with category lookups.
> Add Celery task for sending order confirmation
emails asynchronously. Use Redis as broker.
Django Tips
- Mention your Django version - Patterns differ between 3.x and 4.x
- Specify DRF if using it - Claude Code adjusts for REST framework
- Reference existing patterns - "Follow the same pattern as our UserSerializer"
Flask Development
Creating Flask APIs
> Create a Flask API for a todo application:
- SQLAlchemy models for todos and users
- Blueprint structure
- JWT authentication
- CRUD endpoints
- Swagger documentation
Claude Code creates properly structured Flask code:
# app/routes/todos.py
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models import Todo
from app.schemas import TodoSchema
todos_bp = Blueprint('todos', __name__)
@todos_bp.route('/', methods=['GET'])
@jwt_required()
def get_todos():
user_id = get_jwt_identity()
todos = Todo.query.filter_by(user_id=user_id).all()
return jsonify(TodoSchema(many=True).dump(todos))
Flask-Specific Prompts
> Add rate limiting to the API using flask-limiter.
Limit to 100 requests per minute per user.
> Create a Blueprint for user management with
profile update, password change, and account deletion.
FastAPI Development
Creating FastAPI Services
> Create a FastAPI service for inventory management:
- Pydantic models for products and inventory
- Async database operations with SQLAlchemy
- Background tasks for inventory alerts
- OpenAPI documentation
Claude Code generates modern async FastAPI code:
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from pydantic import BaseModel
class ProductCreate(BaseModel):
name: str
sku: str
quantity: int
class Config:
from_attributes = True
@app.post("/products/", response_model=ProductResponse)
async def create_product(
product: ProductCreate,
db: AsyncSession = Depends(get_db)
):
db_product = Product(**product.model_dump())
db.add(db_product)
await db.commit()
await db.refresh(db_product)
return db_product
FastAPI-Specific Prompts
> Add WebSocket endpoint for real-time inventory
updates. Broadcast changes to all connected clients.
> Implement dependency injection for database
sessions with proper connection pooling.
Data Science Workflows
Data Analysis
> Analyze the sales data in data/sales.csv:
- Load and clean the data
- Calculate monthly trends
- Identify top-performing products
- Create visualization with matplotlib
- Export summary to Excel
Machine Learning
> Create a customer churn prediction model:
- Load customer data from the database
- Feature engineering
- Train/test split with stratification
- Try RandomForest and XGBoost
- Evaluate with precision, recall, F1
- Save best model with joblib
Jupyter Integration
> Convert the analysis in notebooks/exploration.ipynb
into a production-ready Python module with:
- Proper function structure
- Type hints
- Logging
- Error handling
Testing with pytest
Creating Tests
> Write comprehensive tests for the UserService:
- Unit tests for all methods
- Integration tests for database operations
- Fixtures for test data
- Mocks for external services
Claude Code generates pytest-style tests:
import pytest
from unittest.mock import Mock, patch
from app.services import UserService
class TestUserService:
@pytest.fixture
def user_service(self, db_session):
return UserService(db_session)
@pytest.fixture
def sample_user(self):
return {"email": "test@example.com", "name": "Test User"}
def test_create_user_success(self, user_service, sample_user):
user = user_service.create_user(**sample_user)
assert user.email == sample_user["email"]
assert user.id is not None
def test_create_user_duplicate_email_fails(self, user_service, sample_user):
user_service.create_user(**sample_user)
with pytest.raises(DuplicateEmailError):
user_service.create_user(**sample_user)
Test-Specific Prompts
> Add test coverage for edge cases:
- Empty inputs
- Invalid data types
- Concurrent operations
- Network failures
Automation Scripts
Creating Scripts
> Create a script to:
- Monitor a directory for new CSV files
- Validate file format
- Load data into PostgreSQL
- Send Slack notification on completion
- Log all operations
Script Improvements
> Add to the existing backup script:
- Retry logic with exponential backoff
- Parallel processing for multiple files
- Progress bar with tqdm
- Email report on completion
Type Hints and Modern Python
Claude Code generates properly typed code:
from typing import Optional, List
from pydantic import BaseModel
def get_users(
skip: int = 0,
limit: int = 100,
active_only: bool = True
) -> List[User]:
"""Retrieve users with optional filtering."""
query = User.query
if active_only:
query = query.filter(User.is_active == True)
return query.offset(skip).limit(limit).all()
Prompt for Types
> Add comprehensive type hints to the utils module.
Use modern Python 3.10+ syntax where appropriate.
Python-Specific Tips
1. Mention Your Python Version
> We're using Python 3.11. Create a script using
the new tomllib for config parsing.
2. Specify Your Dependency Manager
> Add the new dependency to pyproject.toml.
We use Poetry for package management.
3. Reference Virtual Environment
> The virtual environment is in .venv.
Install the new package there.
4. Follow PEP 8
Claude Code follows PEP 8 by default, but you can reinforce:
> Ensure all code follows PEP 8 and passes flake8.
5. Use Existing Patterns
> Create a new service class following the same
pattern as our existing OrderService.
Common Python Tasks
| Task |
Prompt |
| New endpoint |
"Add a GET endpoint for /products/{id}" |
| Database model |
"Create a model for user subscriptions" |
| Migration |
"Generate migration for the new model" |
| Async conversion |
"Convert this view to async" |
| Add caching |
"Add Redis caching to the product list" |
| Error handling |
"Add proper exception handling to the service" |
| Logging |
"Add structured logging throughout" |
| Documentation |
"Add docstrings to all public functions" |
Performance Optimization
> Profile and optimize the generate_report function.
It's currently taking 30 seconds for 10k records.
Claude Code will:
- Analyze the code
- Identify bottlenecks
- Suggest optimizations (batching, caching, async)
- Implement improvements
The Bottom Line
Claude Code understands Python deeply:
- Framework conventions (Django, Flask, FastAPI)
- Modern Python patterns (async, type hints)
- Testing best practices (pytest, fixtures, mocks)
- Data science workflows (pandas, sklearn)
The key is being specific about your project's patterns and preferences. Claude Code adapts to your codebase, not the other way around.
Building Python applications and need operations support? Cedar Operations helps teams optimize their development workflows. Book a consultation →
Related reading: