Skip to content

Claude Code for Python: A Complete Guide

Claude Code is a coding agent that reads your files, runs commands, edits code, and iterates on errors. Describe what you want in plain English, and Claude Code determines which files to read, which commands to run, and what code to write. When something breaks, it reads the error, adjusts, and tries again.

This guide covers how to use Claude Code for Python development specifically. Each section is self-contained, so skip to whatever is relevant.

Why Claude Code for Python development

Claude Code closes the gap between “I want to build something” and “I have a working project.” Tell it what you want to build and it installs the right tools, creates the project structure, writes the initial code, and runs it within the session’s permission settings. When it hits an error, it reads the traceback and proposes a fix without you needing to interpret the error message yourself.

Claude Code operates at the project level: it creates files, installs packages, runs tests, and makes multi-file changes in a single request. It takes action directly in your terminal rather than suggesting code to copy-paste. You can use it alongside an editor; they serve different roles.

Tip

Already have Claude Code installed? The highest-leverage Python setup step is a CLAUDE.md that pins your tooling so Claude uses uv and Ruff by default. See how to configure Claude Code to use uv.

Installation

Claude Code runs in your terminal. Install it with the native installer:

curl -fsSL https://claude.ai/install.sh | bash

Open a new terminal and run claude --version; it should print the installed version. Run claude to sign in with an eligible account. Native installations update automatically; package manager installations follow their own update process.

Important

Navigate to your project directory before launching. Claude Code reads the files in your current working directory to build context. Launching from your home directory means it will not know about your project.

cd my-project
claude

To end a session, type /exit or press Ctrl+C.

Permissions and approvals

Permission modes and rules control which actions require approval. Open /permissions to inspect the active rules. Project instructions describe what Claude should try; permission settings control what it may execute.

  • default prompts for tool calls that require approval and have no matching allow rule.
  • acceptEdits accepts routine file edits while retaining command approval checks.
  • plan explores the project before implementation. Ask for a plan, review it, then approve the work.
  • auto, where available, checks proposed actions with a background classifier and reduces routine prompts.

Sandboxing adds filesystem and network restrictions for shell commands. It is a separate control from approval prompts. Read commands when prompted and review the final diff even when actions ran without a prompt.

Costs and token usage

Claude Code consumes resources with every interaction. API users pay per token; subscribers consume usage against their plan limits. Each iteration through the build-run-fix cycle involves reading files, generating code, and processing command output, so agentic workflows use resources fast.

  • Check API costs with /cost. Subscribers can use /usage to inspect plan usage limits.
  • Choose a model. Use /model to switch between available models. Smaller models use fewer resources and work well for straightforward tasks.
  • Keep sessions focused. A session that wanders across many unrelated tasks uses resources faster than necessary. Start a new session when you shift to a different task.

Slash commands

Claude Code has built-in commands that start with /. The most useful ones for daily work:

  • /help shows all available commands.
  • /init generates a CLAUDE.md file for your project based on its structure.
  • /compact summarizes the conversation to free up context space. See Context window limits for when to use this.
  • /cost shows token usage for the current session.
  • /model switches between available Claude models.
  • /clear resets the conversation and starts fresh.
  • /exit ends the session.

Setting up Python with Claude Code

Python does not need to be installed before starting. Ask Claude Code to handle it:

Install uv and create a new Python project called my-app

Claude Code will install uv, which handles three things that trip up new Python developers:

Python versions. Python releases new versions regularly, and different projects may need different versions. uv downloads and manages Python interpreters so you don’t need to install Python from a website or wrestle with system package managers.

Virtual environments. A virtual environment keeps each project’s packages separate, so installing a package for Project A can’t break Project B. In uv projects, uv run and uv sync create and manage them automatically.

Packages. Python’s strength is its library ecosystem: uv installs packages faster than pip and tracks what your project depends on in a structured file. For a deeper look, see the Complete Guide to uv.

How to give good instructions

Concrete instructions produce better results than abstract ones.

Instead of “Make this code better,” try “This function is slow when the input list has more than 10,000 items. Find a faster approach.”

Instead of “Build me a web app,” try “Create a FastAPI app with one endpoint, /greet, that takes a name query parameter and returns a JSON greeting.”

  • Include the goal alongside the task. “I’m building a CLI that processes CSV files” gives Claude Code context to make better decisions than “write a function that reads a CSV.”
  • Mention constraints. “Use only the standard library” or “this needs to run on Python 3.10” prevents wasted iteration.
  • Describe what’s wrong instead of starting over. If Claude Code produces output that’s close but not right, name the gap: “The output format is correct but the dates should be ISO 8601.”

The build-run-fix cycle

Claude Code automates the write-run-fix loop. It writes code, executes it, reads the traceback when something fails, edits the code, and reruns. You watch the cycle happen in your terminal.

Professional developers spend much of their time in this same loop. The difference is speed. Claude Code can go through several iterations in the time it would take to manually interpret an error message and look up the fix.

When to let it iterate:

  • The errors are getting shorter or changing (progress is happening).
  • It’s working through import errors, typos, or missing dependencies.

When to step in:

  • It’s trying the same fix repeatedly.
  • The approach seems wrong, not just the details. Say “stop” and redirect: “Try a different approach. Use X library instead.”

Context window limits

Every model has a finite context window, and longer sessions fill it up. Claude Code auto-compacts when it approaches the limit, but quality can still degrade as earlier details get summarized away.

Watch for these signs:

  • Claude Code re-reads files it already examined.
  • It suggests changes you already rejected.
  • Responses become less relevant to your current task.

When this happens, use /compact to summarize the conversation history and reclaim context space. For a major topic change, start a fresh session with /clear or open a new terminal.

Tip

Short, focused sessions produce better results than marathon ones. If you are switching to a different task, start a new session.

Ask Claude Code to explain

You can ask Claude Code to explain anything it writes, at any time:

What does this function do?
Walk me through how this project is structured and why.
Explain the error handling in app.py

Understanding what the code does is essential for maintaining and debugging it later. Ask Claude Code to explain unfamiliar syntax, library choices, or design patterns as they come up.

Project structure

When Claude Code scaffolds a Python project intended to be imported as a library or package, it typically uses a src/ layout. The src/ directory prevents accidental imports from the project root during development. After running uv init --package, adding dependencies, and creating a test file, the structure looks like this:

    • pyproject.toml
    • uv.lock
        • __init__.py
        • main.py
      • test_main.py

Tip

uv init produces the src/my_app/ package with a single __init__.py by default; main.py and tests/ come from the later steps. --no-package keeps the project layout flat (a main.py at the top level instead of a src/ package). For a full comparison of the available layouts, see Understanding uv init project types.

pyproject.toml is the project’s configuration file. It lists the project name, Python version requirement, and direct dependencies. See Why choose pyproject.toml over requirements.txt? for background.

uv.lock is a lockfile that records the exact version of every dependency resolved for the project. This helps ensure reproducible installs across machines.

src/ contains your source code. The nested folder with __init__.py is a Python package.

tests/ contains automated tests. Keeping tests in a separate directory from source code is standard Python convention.

For a hands-on walkthrough, see the tutorial Create your first Python project.

Working with packages

Python’s library ecosystem is one of the language’s biggest strengths. When you need to make HTTP requests, parse dates, build a web server, or analyze data, there’s almost certainly a package for it.

Package names are not required upfront. Describe what you need:

I need to make HTTP requests to a REST API. Add the right package.

With uv recorded in your project instructions, Claude Code should propose an appropriate library such as httpx and install it with uv add. Review the choice and the resulting dependency changes. The dependency gets recorded in pyproject.toml so it’s tracked with the project.

To understand how dependency management works in detail, see the Complete Guide to uv.

CLAUDE.md and AGENTS.md: Standing instructions

A CLAUDE.md file in your project root gives Claude Code standing instructions it reads at the start of every session. For Python projects, this is the place to specify which tools to use, how to run tests, and any project conventions.

Claude Code also reads AGENTS.md when there is no CLAUDE.md, .claude/CLAUDE.md, or CLAUDE.local.md in the working directory or its ancestors. Open /config and change Project instructions if you want both file types loaded. If that setting is unavailable, check the instruction-loading guidance or import AGENTS.md from CLAUDE.md.

A realistic example:

# Project conventions

- Python >= 3.11
- Use uv for all package management (never pip)
- Use src/ layout (uv init --package)
- Run tests with: uv run pytest
- Run linting with: uv run ruff check .
- Format code with: uv run ruff format .
- Type check with: uv run ty check src/

## Code style

- Prefer httpx over requests for HTTP calls
- Use pathlib for file paths, not os.path

Keep the instruction file short and factual. It should contain instructions that apply to every session, not one-time tasks. Commit it to version control so every collaborator gets the same behavior.

Tip

Run /init inside Claude Code to generate a starter CLAUDE.md based on your project’s structure. Then customize it with your conventions.

For a shared Codex and Claude Code template, see How to Write AGENTS.md for a Python Project. For a Claude-specific setup, see How to configure Claude Code to use uv. For a comprehensive set of project scaffolding instructions you can paste into an instruction file or a Claude Code session, see the Modern Python Project Setup Guide for AI Assistants.

Run the project checks

Give Claude the commands your project already uses, then ask it to run them before and after a change:

Run uv run pytest --tb=short -q before changing src/my_app/parser.py.
After the change, rerun the affected tests and then the full suite.
Report the commands and any failures that remain.

uv run executes the command inside the project’s virtual environment, ensuring all dependencies are installed first. A failing baseline separates existing problems from regressions. A targeted rerun gives fast feedback; the full suite catches effects outside the changed module.

A passing pytest run ends with a summary such as 5 passed. Read failures before allowing the agent to change test expectations. Keep the same checks in CI so verification also runs outside Claude Code sessions.

See configure Claude Code to run pytest for an on-demand skill and a bounded hook.

Add skills, subagents, and hooks when needed

Choose an extension for the job it performs:

  • Put short project-wide commands in CLAUDE.md or the repository’s supported AGENTS.md.
  • Use .claude/rules/ for instructions that apply to particular paths, such as packaging or test configuration.
  • Use skills for a reusable procedure. Invoke /skill-name directly or let Claude select a skill from its description.
  • Use subagents for a focused investigation with its own context. Their tool access is configurable; delegation does not by itself create a filesystem sandbox.
  • Use hooks for event-driven commands, such as formatting an edited Python file. A hook runs in the environment hosting the session and needs its tools installed there.

A local setup does not provision a cloud session. For remote or cloud work, install dependencies and run the same project checks in that environment before relying on its results.

Linting and formatting

A linter scans your code for common mistakes, style violations, and potential bugs. A formatter rewrites your code to follow consistent style rules (indentation, spacing, line length). Together, they keep code clean and readable.

Ruff handles both jobs. Ask Claude Code to set it up:

Add ruff to this project and configure it for linting and formatting

Once configured, you can ask Claude Code to check and fix your code:

Run ruff on the project and fix any issues

Consistent formatting helps when learning. It enforces uniform indentation and spacing across your codebase, making code easier to read and reducing style-related confusion.

For a full walkthrough, see the tutorial Set up Ruff for formatting and checking your code or the Complete Guide to Ruff.

Git integration

Claude Code understands git. It can read diffs, stage files, write commit messages, and create pull requests. For Python projects, this means you can ask it to handle version control as part of your workflow:

Commit these changes with a descriptive message
Show me what changed since the last commit
Create a pull request for this feature branch

Claude Code reads the diff before writing a commit message, so the message reflects the actual changes rather than a generic summary. When creating pull requests, it can generate a description based on the commits in the branch.

Note

By default, Claude Code prompts for approval before running git commands that modify history or push to a remote. This depends on your permission configuration.

When Claude Code gets it wrong

Claude Code will write broken code, choose the wrong library, overcomplicate a solution, or misunderstand what you asked. This is expected.

Common mistakes to watch for:

Warning

Always review the proposed command or diff before approving. This is where most mistakes are caught.

  • Using pip install instead of uv add. Without a CLAUDE.md or AGENTS.md that says otherwise, Claude Code may default to pip. Check the commands it proposes before approving.
  • Adding unnecessary dependencies. Claude Code sometimes pulls in a library for something the standard library handles. If you see an unfamiliar package in uv add, ask why it’s needed.
  • Hallucinating library APIs. Claude Code may call functions or use parameters that don’t exist in the library version you’re using. If code fails with AttributeError or TypeError on a library call, this is likely the cause.
  • Changing build configuration. It may change how your project is packaged, add tool sections to pyproject.toml, or restructure your project in ways you didn’t ask for. Review diffs before approving.
  • Writing code that passes tests but is subtly wrong. Tests only catch what they test for. If Claude Code writes both the code and the tests, the tests may not cover edge cases. Read the implementation, not just the test results.

How to redirect:

  • “Simplify this.” If the solution is more complex than it needs to be, say so directly. Claude Code tends toward over-engineering when the prompt is vague.
  • “Try without that library.” If it pulled in a dependency you don’t want, tell it to use the standard library or a specific alternative.
  • “That’s not what I meant. I want X, not Y.” Restate the requirement. Being specific about the gap between what you got and what you wanted is faster than starting over.

Always review the diff before approving changes. Your judgment is part of the process.

Debugging

When Python code fails, it produces a traceback: a stack of messages showing where the error occurred and what went wrong. Tracebacks follow a consistent format: the last line is the error type and message, and the earlier lines show the chain of function calls that led to it.

When you encounter an error, share the context:

I ran the app and got this error. The traceback is below:
[paste the error]

Or, if Claude Code ran the command itself, it already has the error output and will start diagnosing without you pasting anything.

Giving context about what changed helps narrow the problem:

This worked before I added the caching logic. The error started after that change.

Claude Code handles common Python errors well: ImportError, TypeError, KeyError, missing dependencies, version mismatches. It reads the traceback, identifies the root cause, and proposes a fix.

Working with existing code

Claude Code can work with projects you didn’t create. Point it at an existing codebase and ask questions:

Explain the structure of this project. What are the main modules and how do they connect?
What does the process_order function in orders.py do?

When making changes to unfamiliar code, use tests as a safety net:

Run the existing tests, then change the date format in the report generator to ISO 8601

If the project has tests, you can ask Claude Code to run them before and after the change. If a test breaks, it can identify the problem and propose a fix. If the project has no automated checks, establish a reproducible command that exercises the behavior before asking for a change.

Pick your next step

Last updated on