Claude Code prompts for Python help you use Anthropic's terminal-native coding agent on real Python work — type-hint sweeps, pytest scaffolding, async migrations, FastAPI endpoints, Dockerfile creation — without letting the tool loose on your repo unsupervised. Every prompt below is written for US Python teams shipping production code: mypy runs on strict, pytest is the test runner, Black and Ruff enforce style in CI, dependencies are pinned with uv or poetry, and PRs are reviewed before merging. The prompts assume you are running claude in a checked-out repo and letting it plan-then-edit.
These templates are opinionated about the modern Python stack. HTTP calls are httpx (not requests). Data models are Pydantic v2 (not v1 — the migration matters). Logging is structlog with JSON output. Async is asyncio with anyio-friendly patterns. Type checking is mypy --strict, and where mypy is too rigid, pyright in strict mode. Every prompt starts with 'Act as a US Python developer using Claude Code.' so the agent stays in a working-developer voice rather than tutorial mode.
This content is technical guidance for working developers, not a substitute for reading the diff. Claude Code can and will edit files, run shell commands, and hit the network. Before running it in a repo, confirm your team's AI tooling policy, add sensitive paths to .gitignore and to Claude Code's ignore config, and never approve a tool call that reaches production infrastructure or writes secrets. Treat every generated commit like an intern's first PR: read it, run the tests, and never merge code you cannot explain.
Claude Code prompts for Python help you use Anthropic's terminal-native coding agent on real Python work — type-hint sweeps, pytest scaffolding, async migrations, FastAPI endpoints, Dockerfile creation — without letting the tool loose on your repo unsupervised. Every prompt below is written for US Python teams shipping production code: mypy runs on strict, pytest is the test runner, Black and Ruff enforce style in CI, dependencies are pinned with uv or poetry, and PRs are reviewed before merging. The prompts assume you are running claude in a checked-out repo and letting it plan-then-edit.
These templates are opinionated about the modern Python stack. HTTP calls are httpx (not requests). Data models are Pydantic v2 (not v1 — the migration matters). Logging is structlog with JSON output. Async is asyncio with anyio-friendly patterns. Type checking is mypy --strict, and where mypy is too rigid, pyright in strict mode. Every prompt starts with 'Act as a US Python developer using Claude Code.' so the agent stays in a working-developer voice rather than tutorial mode.
This content is technical guidance for working developers, not a substitute for reading the diff. Claude Code can and will edit files, run shell commands, and hit the network. Before running it in a repo, confirm your team's AI tooling policy, add sensitive paths to .gitignore and to Claude Code's ignore config, and never approve a tool call that reaches production infrastructure or writes secrets. Treat every generated commit like an intern's first PR: read it, run the tests, and never merge code you cannot explain.
Guides, tips, and deep dives for this prompt category
How to use Claude Code — the terminal-based AI coding agent. Features, pricing, and 15 best prompts.
Read morePromptsCreate stunning Studio Ghibli-style AI art with 50 free prompts for ChatGPT. Magical landscapes, characters, food scenes, and cozy interiors in Miyazaki style.
Read moreCopy any prompt below, paste into ChatGPT, Claude, Gemini, or Copilot, and fill in the placeholders in [brackets].
Act as a US Python developer using Claude Code. Refactor [module path] to use full type hints and pass mypy --strict. Add explicit return types on every function, replace Any with the narrowest concrete type that compiles, use collections.abc for generic containers (Sequence, Mapping, Iterable), add TypedDict or Pydantic v2 models for structured dicts, and add TypeAlias for repeated complex types. Do not use # type: ignore unless you also add a comment explaining why. Show the diff and the mypy output before and after.
Act as a US Python developer using Claude Code. Generate a pytest test file for [function or class name] in [file path]. Cover the happy path, at least three edge cases (empty input, boundary values, invalid types), any raised exceptions (using pytest.raises with a match pattern), and any async behavior with pytest-asyncio. Use parametrize for input/output pairs, fixtures for shared setup, and no mocks unless the function has real side effects. Include a docstring on each test explaining what invariant it protects.
Act as a US Python developer using Claude Code. Fix this pytest failure: [paste pytest -x output including traceback]. Identify whether the failure is a bug in the code under test, a bug in the test itself, a fixture ordering issue, or an environment problem (missing env var, wrong Python version, flaky async). Show the minimal patch, explain why the failure occurred, and add a regression test that would have caught the original bug before the fix.
Act as a US Python developer using Claude Code. Migrate [module path] from the requests library to httpx while preserving behavior. Convert requests.get/post to httpx.get/post for sync callers, or to an httpx.AsyncClient context manager for async callers. Preserve timeout, headers, params, and auth handling. Update retry logic to use httpx-compatible transports or an explicit tenacity wrapper. Update tests: swap requests-mock for respx. Confirm mypy passes and no requests import remains.
Act as a US Python developer using Claude Code. Write an argparse CLI for [use case, e.g. bulk-renaming files, running a data export, seeding a database]. Use subcommands if there is more than one action. Include --help text for every argument, sensible defaults, type coercion (Path, int, float), a --dry-run flag, a --verbose flag that flips logging to DEBUG, and a main() function that returns an int exit code. Put the entrypoint under [module]:main and register it in pyproject.toml.
Act as a US Python developer using Claude Code. Convert [function or module] from sync to async using asyncio. Identify which calls are I/O-bound (network, disk, DB) and worth awaiting versus CPU-bound (keep sync or offload to a thread pool via asyncio.to_thread). Replace requests with httpx.AsyncClient, replace time.sleep with asyncio.sleep, and gather independent awaits with asyncio.gather. Update callers up the stack and confirm no sync code calls the new async function without awaiting.
Act as a US Python developer using Claude Code. Profile [slow function name] in [file path] with cProfile and propose optimizations. Run 'python -m cProfile -s cumulative -o profile.out [entrypoint]' with a representative input, load the result with pstats, and identify the top three cumulative-time hotspots. For each hotspot, suggest the change (algorithmic — better data structure, avoided N+1; or mechanical — cache, batch, vectorize with numpy). Confirm the fix with a before/after timeit measurement.
Act as a US Python developer using Claude Code. Write a Google-style docstring for [function or class name] in [file path]. Include a one-line summary, an extended description if the behavior is non-obvious, Args with types and semantics, Returns with type and meaning, Raises for every exception the caller should handle, and Example with a runnable snippet if the API is not self-explanatory. Do not repeat the type annotations in prose — the docstring should add semantic information, not restate the signature.
Act as a US Python developer using Claude Code. Generate a Pydantic v2 model from this JSON sample: [paste JSON]. Use BaseModel (not v1's BaseModel with validator decorators — use field_validator and model_validator from v2), give every field a proper type, mark optional fields as SomeType | None with a default, use Annotated with Field for constraints (min_length, ge, le, pattern), and add model_config = ConfigDict(extra='forbid') unless the payload has documented optional keys. Include a small round-trip test that parses the sample and dumps it back with model_dump_json().
Act as a US Python developer using Claude Code. Add structlog-based structured logging to [module path]. Configure structlog at the app entrypoint with JSONRenderer for production and ConsoleRenderer for local dev (switched by env var). Replace every existing logging.getLogger call with structlog.get_logger. Bind request-scoped context (request_id, user_id) using bind_contextvars where available. Do not log secrets, tokens, or full request bodies — log field names, not values, for sensitive data.
Act as a US Python developer using Claude Code. Fix a circular import between [module A] and [module B]. Diagnose whether the cycle is genuine (both modules truly depend on each other's runtime symbols) or accidental (one side only needs the type for annotation). For genuine cycles, extract the shared piece into a third module. For type-only cycles, move the import under 'if TYPE_CHECKING:' and use the string form of the annotation. Show the import graph before and after and confirm no import-time side effects remain.
Act as a US Python developer using Claude Code. Write a production Dockerfile for [Python app type — FastAPI service, CLI tool, Celery worker, Django app]. Use a multi-stage build: a builder stage with uv or pip to install into a virtualenv, then a slim runtime stage that copies only the venv and app code. Use python:3.12-slim (not full), run as a non-root user, set PYTHONDONTWRITEBYTECODE and PYTHONUNBUFFERED, expose only the port the app binds to, and set a HEALTHCHECK. Do not run pip install at container startup.
Act as a US Python developer using Claude Code. Generate a FastAPI endpoint for [use case, e.g. POST /users to create a user]. Define request and response Pydantic v2 models (UserCreate, UserRead — never return the ORM object directly), use dependency injection for the DB session, raise HTTPException with the correct status codes (400 for validation, 404 for missing, 409 for conflicts), add a response_model with response_model_exclude_unset where appropriate, and generate a pytest-asyncio test that exercises the happy path and one error path using httpx.AsyncClient.
Act as a US Python developer using Claude Code. Migrate [module path or whole project] from Python 3.9 to 3.12. Replace typing.List/Dict/Tuple/Optional with the built-in generics (list[str], dict[str, int]) and X | None syntax. Replace typing.Union[A, B] with A | B. Adopt match/case where a chain of isinstance checks would be clearer. Verify all dependencies in pyproject.toml declare Python 3.12 support (check with 'pip index versions' or PyPI). Confirm mypy --strict, pytest, and ruff all pass on 3.12.
Understanding the building blocks lets you adapt any prompt to your own creative direction.
Tell the AI who the output is for and what real workplace situation it should support.
Act as a federal program analyst preparing a plain-language memo for agency leadership.Name the exact deliverable: email, memo, checklist, SOP, meeting recap, training note, or status update.
Format the answer as a one-page briefing with bullets, risks, and next actions.Specify whether the output should sound official, executive-ready, plain-language, or employee-friendly.
Use a professional, neutral, public-sector tone suitable for a US agency audience.For government, HR, finance, healthcare, legal, and compliance workflows, accuracy guardrails matter more than clever wording.
Use only the facts below, flag assumptions, and include a section for items that need verification.Ask the model to surface uncertainty so the user can verify sensitive or official information before using it.
Before finalizing, list compliance risks, missing details, and any claims that need human review.Tested on this prompt category as of mid-2026. Ratings reflect quality for Claude Code Prompts for Python specifically.
| Model | Best for | Rating |
|---|---|---|
| ChatGPT (GPT-4o / GPT-5) | Everyday drafting and summaries | |
| Claude Sonnet 4.5 | Long documents and policy | |
| Gemini 2.5 Pro | Grounded in Google workspace | |
| Copilot (M365) | Office 365 integration | |
| Perplexity | Answers with citations |
Ratings reflect suitability for this category. Free tiers available on all listed models. Last tested May 2026 by PromptSpace editors.
Yes for read-only and repo-local tools — pytest, mypy, ruff, black, coverage. These are safe to auto-approve in Claude Code settings and speed up the plan-edit-verify loop dramatically. Do not auto-approve anything that touches the network (pip install from a URL, docker pull), writes outside the repo, or interacts with git remotes. Add those to the always-confirm list so you see every tool call before it runs.
Put a CLAUDE.md file at the repo root listing your conventions: target Python version, package manager (uv or poetry), test layout, docstring style, logging library, and forbidden patterns. Reference your CI config so the agent runs the same commands CI does. For monorepos, add a CLAUDE.md inside each package with locally-relevant rules. This file is durable memory the agent reads every session.
No, and you should not want it to. Break the migration into modules and run one module per session. The v1-to-v2 changes are subtle (validator to field_validator, .dict() to .model_dump(), Config class to model_config = ConfigDict, root validators to model_validator) and mistakes compound. Small scoped sessions with tests passing after each one are safer than one giant PR.
Name the edge cases in the prompt: empty input, unicode, whitespace, boundary values (0, -1, MAX_INT), invalid types, and any exceptions the function raises. Ask for parametrize with input/output pairs rather than one test per case. Then flip an assertion to confirm the test fails when the code is wrong — a test that has never gone red is not really covering anything.
Only if the sensitive paths are excluded from the agent context. Add .env, credentials files, and any customer data fixtures to Claude Code's ignore configuration and to .gitignore. Never approve a tool call that reads a secrets manager, opens a production database connection, or writes to a shared cloud resource. For genuinely sensitive repos, run Claude Code against a scrubbed fork or a synthetic-data branch first.
Learn the basics of creating stunning AI-generated images using prompts from our library.
GuideDiscover the secrets to crafting prompts that produce consistent, high-quality results.
CollectionCopy-paste 100 tested Midjourney v6 prompts: portraits, cinematic, fantasy, product shots & more. Free, updated for 2026 - instant results.
Social MediaCreate scroll-stopping Instagram content with these AI image prompts designed for Reels, Stories, and posts.
Browse our full library of claude code prompts for python — all free, copy-paste ready, no signup.
Or use our AI Prompt Generator to create custom prompts for your exact style in seconds.
Run claude from the root of the repository you want to edit so the agent has the full context of your pyproject.toml, mypy config, and existing patterns. Start every session with a small, scoped task — one module, one bug, one migration step. Claude Code is at its best when the task fits in a single planning turn and a handful of tool calls; sprawling requests like 'add types to the whole codebase' produce shallow changes and burn context.
Always name your Python version, package manager, and test runner in the prompt: Python 3.12, uv (or poetry), pytest with pytest-asyncio, mypy --strict. Otherwise Claude picks defaults that do not match your stack. After every edit, ask Claude to run the affected tests and the type-checker before you review the diff — 'run pytest tests/unit/test_users.py -x and mypy src/users.py, then show me a summary' is a good closing move. Never accept an edit whose tests you have not seen pass.
Before you approve a Claude Code commit, read every hunk of the diff. Python code generated by any LLM has consistent failure modes: overly broad except Exception clauses, mutable default arguments, missing await on async calls, incorrect Pydantic v1-style config on v2 models, and imported names that do not exist. Run ruff check, mypy --strict, and the test suite locally — the agent's summary is a hint, not a guarantee.
For migrations (requests → httpx, Pydantic v1 → v2, sync → async), also run the code against a real endpoint or a representative fixture, not just unit tests. LLMs are especially prone to translating idiomatically wrong — using httpx.get in an async function instead of httpx.AsyncClient, keeping .dict() calls after moving to Pydantic v2 (should be .model_dump()), or calling asyncio.run inside code already running in an event loop. Integration tests catch what unit tests miss.
Claude Code reads a CLAUDE.md file at the repo root (and in subdirectories) as durable instructions for every session in that folder. Put your Python conventions there: target Python version, package manager, style enforcers (black, ruff, isort), test layout (tests/unit and tests/integration), docstring style (Google), logging library (structlog), and forbidden patterns (no from x import *, no bare except, no print statements outside CLI entrypoints). Reference your CI config so the agent runs the same commands CI does.
For larger repos, add a CLAUDE.md inside each package with locally-relevant rules: 'this package is public API, breaking changes require a deprecation cycle' or 'this package is internal, backwards compatibility is not required.' Also list the tools Claude is allowed to auto-run without confirmation (pytest, mypy, ruff) versus tools that always require approval (git push, database migrations, anything that hits production). This is where the agent gets safe enough to actually leave running.
Claude Code's output is a starting point, not a finished commit. The reliable workflow is: prompt → let the agent plan → approve tool calls one at a time on the first pass with the agent → read the full diff → run pytest, mypy, ruff locally → refactor the parts that do not fit your codebase → open the PR. The 'refactor' step is where AI-assisted code becomes production code; skipping it is how you end up with three logging patterns, two error hierarchies, and inconsistent async boundaries in the same service.
Keep a short prompts.md in the repo (or in a shared team doc) with the prompts that produce good output on your stack. When a prompt starts drifting after a Claude model update, tighten it — usually by naming versions ('Pydantic v2, not v1'), forbidding patterns ('do not use .dict(), use .model_dump()'), or adding a small example. Over a few weeks you end up with a small, tested prompt library that your team actually uses, instead of ad-hoc copy-paste from Slack.
Yes for read-only and repo-local tools — pytest, mypy, ruff, black, coverage. These are safe to auto-approve in Claude Code settings and speed up the plan-edit-verify loop dramatically. Do not auto-approve anything that touches the network (pip install from a URL, docker pull), writes outside the repo, or interacts with git remotes. Add those to the always-confirm list so you see every tool call before it runs.
Put a CLAUDE.md file at the repo root listing your conventions: target Python version, package manager (uv or poetry), test layout, docstring style, logging library, and forbidden patterns. Reference your CI config so the agent runs the same commands CI does. For monorepos, add a CLAUDE.md inside each package with locally-relevant rules. This file is durable memory the agent reads every session.
No, and you should not want it to. Break the migration into modules and run one module per session. The v1-to-v2 changes are subtle (validator to field_validator, .dict() to .model_dump(), Config class to model_config = ConfigDict, root validators to model_validator) and mistakes compound. Small scoped sessions with tests passing after each one are safer than one giant PR.
Name the edge cases in the prompt: empty input, unicode, whitespace, boundary values (0, -1, MAX_INT), invalid types, and any exceptions the function raises. Ask for parametrize with input/output pairs rather than one test per case. Then flip an assertion to confirm the test fails when the code is wrong — a test that has never gone red is not really covering anything.
Only if the sensitive paths are excluded from the agent context. Add .env, credentials files, and any customer data fixtures to Claude Code's ignore configuration and to .gitignore. Never approve a tool call that reads a secrets manager, opens a production database connection, or writes to a shared cloud resource. For genuinely sensitive repos, run Claude Code against a scrubbed fork or a synthetic-data branch first.