惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Stack Overflow Blog
Stack Overflow Blog
量子位
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
美团技术团队
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
Recent Announcements
Recent Announcements
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Microsoft Security Blog
Microsoft Security Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
酷 壳 – CoolShell
酷 壳 – CoolShell
J
Java Code Geeks
V
V2EX
大猫的无限游戏
大猫的无限游戏
D
DataBreaches.Net
博客园 - Franky
爱范儿
爱范儿
T
Tailwind CSS Blog
A
About on SuperTechFans
Google DeepMind News
Google DeepMind News
博客园_首页
B
Blog RSS Feed
博客园 - 司徒正美
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
The Claude Code config files I actually use in Python pro...
Peyton Green · 2026-04-30 · via DEV Community

Most Claude Code advice is about prompting.

I've found the leverage is somewhere else: the config layer. The files that tell Claude Code how to behave before you ask it to do anything.

After six months of daily Claude Code use across Python API projects, data pipelines, and agent builds, here are the config files I actually use — and what each one does.


The CLAUDE.md problem

A blank CLAUDE.md is worse than no CLAUDE.md.

I tried the "just dump your stack into it" approach first. Claude Code read it and mostly ignored the parts that mattered. The problem: CLAUDE.md needs to tell Claude Code what to do and what not to do — not just what your stack is.

The structure that works for me:

## Stack
[versions + tools — so it doesn't guess]

## Project structure
[directory layout — so it knows where things belong]

## Conventions
[the rules that aren't obvious from the code]

## What to do when [common task]
[explicit workflow — the thing you'd tell a new dev on day one]

## What to avoid
[the list of things it'll do wrong without guidance]

## Before committing
[the checklist — ruff, mypy, pytest]

Enter fullscreen mode Exit fullscreen mode

The "what to do when" and "what to avoid" sections are the highest leverage. They encode the decisions you'd otherwise explain repeatedly.

I maintain five templates — one for each project type I work in.


Template 1: Python API / FastAPI

The core conventions for a FastAPI project:

## Conventions

**Routes:** Keep route handlers thin. No business logic in handlers — call service functions.

**Schemas:** Use separate request/response schemas. Never return SQLAlchemy model objects directly.

**Error handling:** Raise HTTPException with meaningful detail strings. Log at ERROR level before raising.

Enter fullscreen mode Exit fullscreen mode

The "never return SQLAlchemy models directly" line prevents a whole class of serialization bugs that are annoying to debug after the fact.

Full template: [in the config pack]


Template 2: Data pipeline

Idempotency and data contracts are the conventions that save you at 3am:

**Idempotency:** Every pipeline step must be safe to re-run. Writes should be upserts or write-to-temp-then-rename.

**Explicit data contracts:** Use Pydantic models at every stage boundary. Never pass raw dicts between pipeline stages.

**Logging:** Log record counts at each stage: extracted N, transformed N, loaded N.

Enter fullscreen mode Exit fullscreen mode

That last one is a simple addition that turns silent failures into obvious ones.


Template 3: LLM agent / AI app

Two conventions that prevent the most common agent bugs:

**Structured outputs everywhere:** Use Pydantic models for all agent inputs and outputs. Never parse free-text agent responses manually.

**Observability:** Log every agent invocation: model, prompt tokens, completion tokens, tool calls made, structured output. Costs are invisible without this.

Enter fullscreen mode Exit fullscreen mode

The observability line stops you from running up unexpected API costs and having no idea why.


Template 4: Test-heavy project (the pytest-centric template)

The fixture naming convention that I always forget to explain:

**Naming:** Fixtures that return objects are nouns (`user`, `db_session`, `api_client`). Fixtures that perform actions are verbs (`create_user`, `seed_database`).

**No fixture logic in test functions:** If setup code exceeds 3 lines, it belongs in a fixture.

Enter fullscreen mode Exit fullscreen mode

And the parametrize guidance:

Use `@pytest.mark.parametrize` for:
- Multiple input/output pairs on the same logic path
- Edge cases (empty string, None, 0, max value)
- Error conditions with different error types

Don't parametrize across fundamentally different behaviors — write separate tests.

Enter fullscreen mode Exit fullscreen mode

This last distinction is the one that takes the most explanation — Claude Code will over-parametrize without it.


Template 5: Multi-service / team

This one is about restricting autonomy, not expanding it:

**You must ask before:**
- Creating new files outside the service directory you were asked to work in
- Modifying anything in `libs/` — shared libraries affect all services
- Changing database migrations
- Installing new dependencies

Enter fullscreen mode Exit fullscreen mode

In shared codebases, conservative defaults plus an explicit ask-first list produces fewer surprises than the default behavior.


Hooks that actually change the workflow

The three hooks I've kept running:

pre-edit-check.sh

Runs ruff + mypy on a file before Claude Code edits it.

Why: if there are type errors in the existing code, Claude Code will sometimes work around them in ways that make things worse. Surfacing them first means it has the full picture.

# In settings.json:
"hooks": {
  "PreToolUse": [
    {
      "matcher": "Edit",
      "hooks": [{ "type": "command", "command": ".claude/hooks/pre-edit-check.sh" }]
    }
  ]
}

Enter fullscreen mode Exit fullscreen mode

post-edit-test.sh

Finds the pytest test file corresponding to the edited module and runs it automatically.

Assumes the convention tests/unit/test_<module>.py<module>.py. If you use a different convention, edit the path lookup:

# In the hook script:
for pattern in \
  "tests/unit/test_${BASENAME}.py" \
  "tests/test_${BASENAME}.py" \
  "test_${BASENAME}.py"
do
  if [[ -f "$pattern" ]]; then
    TEST_FILE="$pattern"
    break
  fi
done

Enter fullscreen mode Exit fullscreen mode

context-logger.sh

Appends every file Claude Code touches to .claude-session.log:

2026-03-27T14:23:01Z | Edit | app/services/user_service.py
2026-03-27T14:23:14Z | Write | tests/unit/test_user_service.py

Enter fullscreen mode Exit fullscreen mode

Useful for reviewing what actually changed at the end of a long session, or auditing before commit.


Slash commands worth having

Five commands I've kept around:

/py-review — Python-specific code review. Checks types, error handling, resource management, idioms, and test coverage gaps. Not a general review — specifically for Python patterns that generic review prompts miss.

/gen-tests — Generates pytest tests with the right structure: one happy path, edge cases, error cases, parametrize where appropriate. The key instruction is what not to do — "no mocking of code I own" and "each test must have exactly one logical assertion."

/debug-async — Async bugs follow a short list of patterns (sync-in-async, unwaited tasks, swallowed CancelledError, race conditions on shared state). The command works through them systematically instead of random debugging.

/refactor-safe — Forces a plan before touching anything. Makes Claude Code identify every caller before changing a signature, agree on the target shape, and do changes one step at a time.

/pre-deploy — Walks through environment variables, error handling, logging, rate limiting, database safety, and secrets. Five minutes before a deploy to catch the things you can't test locally.

All five drop into .claude/commands/ and appear as slash commands.


Subagent patterns

Two patterns that work well for longer projects:

Research → implement → review as three separate Claude Code passes. The research pass is read-only (structured findings output). The implementation pass works from the research output. The review pass is a fresh context that only sees the finished code.

The reviewer subagent specifically works better as a separate dispatch because it has no context about why the implementation made particular choices — which is exactly the perspective you want in a reviewer.

Test writer as a separate pass after implementation is complete. Reading the finished implementation and writing tests for the actual behavior produces better coverage than writing tests and implementation simultaneously.


Where to start

If you're not already using CLAUDE.md templates: pick the template that matches your main project type, drop it in, edit the stack section and directory structure. That alone cuts the number of times you have to re-explain conventions.

If you already have CLAUDE.md: add a "What to avoid" section. List the three things Claude Code does wrong most often in your codebase. It'll stop doing them.

Hooks are optional but context-logger.sh is zero-friction — it just runs in the background and gives you a session audit trail.


The full config pack (CLAUDE.md templates, settings.json presets, hooks, slash commands, subagent templates) is available at https://kazdispatch.gumroad.com/l/claude-code-python-config — $29 one-time.

Everything in this article is free to use as-is — the pack is for the files themselves, ready to drop in.