Beyond Autocomplete: 12 Python Prompts That Turn AI Into Your Senior Pair Programmer
Most developers use AI like a slightly smarter autocomplete: type a comment, get a snippet, move on. But a well-crafted prompt can do far more — it can generate a fully typed FastAPI endpoint with dependency injection, refactor a 500-line legacy script into clean modules, or write pytest fixtures that actually catch edge cases. The difference is structure. In this article, I’ll share 12 battle-tested prompts for daily Python work, each with a template, a real example, and an explanation of when to use it. These are the prompts I use when working with FastAPI, pandas, asyncio, and mypy — and they’ve saved me hours of boilerplate and debugging.
1. Generate a Typed FastAPI Endpoint with Pydantic Models
Task: Create a new REST endpoint with request/response validation, error handling, and OpenAPI docs.
Prompt:
You are a senior Python developer. Generate a FastAPI endpoint for [resource] with the following requirements:
- Use Pydantic v2 models for request and response.
- Include validation for [field constraints].
- Add dependency injection for a database session.
- Handle errors with HTTPException and custom error messages.
- Return a 201 status code on creation.
- Add a docstring and type hints.
Example:
from fastapi import FastAPI, HTTPException, Depends, status
from pydantic import BaseModel, Field
from typing import Annotated
app = FastAPI()
class ItemCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=100)
price: float = Field(..., gt=0)
class ItemResponse(ItemCreate):
id: int
async def get_db():
# simulate DB session
yield "db_session"
@app.post("/items/", response_model=ItemResponse, status_code=status.HTTP_201_CREATED)
async def create_item(item: ItemCreate, db: Annotated[str, Depends(get_db)]):
"""Create a new item."""
if item.name == "duplicate":
raise HTTPException(status_code=400, detail="Item already exists")
return ItemResponse(id=1, **item.model_dump())
When to use: When scaffolding a new API or adding endpoints quickly while maintaining type safety.
2. Refactor Legacy Code into Clean Modules
Task: Take a monolithic script and split it into maintainable functions/classes with type hints.
Prompt:
Refactor the following Python script into a clean, modular structure. Extract reusable functions, add type hints, docstrings, and separate concerns. Output the refactored code with a brief explanation of changes.
Example:
Input: a 100-line script that reads CSV, processes data with pandas, and writes JSON.
Output: functions load_data(path: str) -> pd.DataFrame, process_data(df: pd.DataFrame) -> pd.DataFrame, save_json(df: pd.DataFrame, path: str) -> None, each with docstrings and type hints.
When to use: When inheriting legacy code or preparing a script for production.
3. Write Pytest Fixtures and Parametrized Tests
Task: Generate comprehensive tests for a function, including edge cases.
Prompt:
Write pytest tests for the function `[function_name]`. Include:
- Fixtures for setup/teardown.
- Parametrized tests for normal and edge cases.
- Mocking of external dependencies.
- Assertions for expected exceptions.
Example:
import pytest
from mymodule import divide
@pytest.fixture
def valid_inputs():
return [(10, 2, 5.0), (9, 3, 3.0)]
@pytest.mark.parametrize("a, b, expected", valid_inputs())
def test_divide_valid(a, b, expected):
assert divide(a, b) == expected
def test_divide_by_zero():
with pytest.raises(ValueError, match="Cannot divide by zero"):
divide(1, 0)
When to use: When adding tests to existing code or practicing TDD.
4. Optimize pandas Operations for Performance
Task: Speed up slow DataFrame operations.
Prompt:
Optimize the following pandas code for performance. Suggest vectorized alternatives to loops, use built-in methods, and explain the time complexity improvements. Provide the optimized code.
Example:
Input: for i in range(len(df)): df.loc[i, 'new'] = df.loc[i, 'a'] + df.loc[i, 'b']
Output: df['new'] = df['a'] + df['b']
When to use: When working with large datasets and noticing slow execution.
5. Debug asyncio Errors and Race Conditions
Task: Identify and fix issues in asynchronous code.
Prompt:
Analyze the following asyncio code for potential race conditions, deadlocks, or unhandled exceptions. Suggest fixes and explain the concurrency model. Provide corrected code with comments.
Example:
Input: two coroutines modifying a shared list without locks.
Output: use asyncio.Lock() and wrap critical sections.
When to use: When writing concurrent code with asyncio and encountering flaky tests.
6. Add Type Hints and Pass mypy --strict
Task: Add complete type annotations to a module.
Prompt:
Add type hints to the following Python code to make it pass mypy --strict. Use typing constructs like Optional, Union, Callable, TypeVar where needed. Explain any tricky annotations.
Example:
Input: def process(data): return data[0]
Output: from typing import List, TypeVar\nT = TypeVar('T')\ndef process(data: List[T]) -> T: return data[0]
When to use: When preparing code for production or enforcing type safety.
7. Generate SQL Queries with SQLAlchemy Core/ORM
Task: Create complex queries safely.
Prompt:
Write a SQLAlchemy query to [describe goal]. Use the ORM, include joins, filters, and ordering. Ensure it’s safe from SQL injection and add type hints.
Example:
from sqlalchemy import select
from models import User, Order
stmt = select(User.name, func.sum(Order.amount)).join(Order).group_by(User.id).having(func.sum(Order.amount) > 1000)
When to use: When building data access layers with SQLAlchemy.
8. Convert Scripts to CLI Tools with argparse/click
Task: Turn a script into a user-friendly command-line tool.
Prompt:
Convert the following script into a CLI tool using [argparse/click]. Add arguments, options, help text, and error handling. Provide the full code.
Example:
import click
@click.command()
@click.option('--input', required=True, type=click.Path(exists=True))
@click.option('--output', default='output.json')
def process(input, output):
"""Process input file and save to output."""
click.echo(f"Processing {input} -> {output}")
When to use: When sharing scripts with teammates or automating tasks.
9. Write Dockerfile and docker-compose for Python App
Task: Containerize a Python application efficiently.
Prompt:
Create a Dockerfile and docker-compose.yml for a Python [FastAPI/Flask] app. Use multi-stage builds, minimize image size, and include health checks. Explain each step.
Example:
FROM python:3.11-slim as builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user -r requirements.txt
FROM python:3.11-slim
COPY --from=builder /root/.local /root/.local
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0"]
When to use: When deploying Python apps to containers.
10. Generate Documentation with Sphinx or MkDocs
Task: Create docstrings and documentation site.
Prompt:
Generate Google-style docstrings for the following functions/classes. Then provide a MkDocs configuration and structure to build a documentation site.
Example:
def add(a: int, b: int) -> int:
"""Add two integers.
Args:
a: First integer.
b: Second integer.
Returns:
The sum of a and b.
"""
return a + b
When to use: When documenting a library or internal project.
11. Refactor to Use Dataclasses or Pydantic Models
Task: Replace boilerplate classes with dataclasses/Pydantic.
Prompt:
Refactor the following class to use @dataclass or Pydantic BaseModel. Add validation, default values, and type hints. Explain the benefits.
Example:
Input: a class with __init__, __repr__, and no types.
Output: @dataclass with fields and types.
When to use: When reducing boilerplate and improving readability.
12. Find and Fix Security Vulnerabilities
Task: Scan code for common security issues.
Prompt:
Analyze the following Python code for security vulnerabilities (SQL injection, XSS, insecure deserialization, etc.). Suggest fixes and provide secure code.
Example:
Input: query = f"SELECT * FROM users WHERE name = '{user_input}'"
Output: use parameterized queries with SQLAlchemy or psycopg2.
When to use: Before deploying to production or during code review.
Comparison Table: Which Prompt for Which Task?
| Task | Prompt # | Key Benefit |
|---|---|---|
| API development | 1 | Fast scaffolding with types |
| Legacy refactoring | 2 | Modular, maintainable code |
| Testing | 3 | Comprehensive test coverage |
| Performance tuning | 4 | Vectorized, faster code |
| Concurrency | 5 | Safe async patterns |
| Type safety | 6 | mypy --strict compliance |
| Database queries | 7 | Secure, efficient SQL |
| CLI tools | 8 | User-friendly interfaces |
| Containerization | 9 | Lightweight Docker images |
| Documentation | 10 | Auto-generated docs |
| Data modeling | 11 | Less boilerplate |
| Security | 12 | Vulnerability fixes |
These prompts are not magic — they work best when you provide context: the code, the constraints, and the expected outcome. Treat AI as a junior developer who needs clear instructions, and you’ll get production-ready results. For further reading, check the official FastAPI docs (fastapi.tiangolo.com), pandas documentation (pandas.pydata.org), and mypy handbook (mypy.readthedocs.io). Start with one prompt today, adapt it to your workflow, and watch your velocity increase.
Comments