Claude Code से Python सीखें: uv, pytest, Ruff और FastAPI गाइड
Claude Code से Python प्रोजेक्ट बनाएं: uv, pyproject.toml, pytest, Ruff, FastAPI और सुरक्षित iteration।
Python में Claude Code का उपयोग करते समय शुरुआती लोगों की सबसे बड़ी समस्या कोड बनवाना नहीं होती। असली समस्या यह होती है कि प्रोजेक्ट सच में चलने लायक है या नहीं: virtual environment सही है या नहीं, imports मिल रहे हैं या नहीं, tests चल रहे हैं या नहीं, और अगली गलती को कैसे समझना है।
इस गाइड में हम एक छोटा task management प्रोजेक्ट बनाएंगे। पहले uv या venv से environment तैयार करेंगे, फिर pyproject.toml में dependencies और tools रखेंगे, FastAPI से छोटी API बनाएंगे, optional CLI जोड़ेंगे, pytest से tests लिखेंगे और ruff से lint तथा format जांचेंगे। Claude Code को बड़े अनुमान लगाने के बजाय इसी छोटे ढांचे में काम कराना ज्यादा सुरक्षित है।
हमेशा official docs देखें: Claude Code docs, Python के लिए pyproject.toml guide, uv installation, pytest, Ruff और FastAPI first steps।
पहले छोटा लक्ष्य तय करें
पहले prompt में authentication, database, Docker और CI सब न मांगें। शुरुआती प्रोजेक्ट में लक्ष्य इतना छोटा होना चाहिए कि error आने पर कारण अलग किया जा सके।
uv run pytestpass होuv run ruff check .औरuv run ruff format .चलें- FastAPI एक task बना और list कर सके
- CLI terminal से एक task जोड़ सके
- Claude Code बताए कि उसने कौन से commands चलाए
flowchart LR
A["काम का brief"] --> B["uv या venv"]
B --> C["pyproject.toml"]
C --> D["src में implementation"]
D --> E["pytest"]
E --> F["ruff"]
F --> G["Claude Code से छोटी iteration"]
Brief यानी coding agent के लिए काम की सीमा। इसमें goal, allowed files, Python version और verification commands लिखें। Repo की स्थायी rules के लिए CLAUDE.md best practices पढ़ें। API बढ़ाने से पहले Claude Code API development और testing के लिए testing strategies भी उपयोगी हैं।
Claude Code के लिए पहला prompt
नीचे वाला prompt copy करके इस्तेमाल किया जा सकता है।
इस repository में Python 3.12 के लिए छोटा task management API जोड़ें।
शर्तें:
- Dependency management के लिए uv use करें और settings pyproject.toml में रखें।
- Implementation src/task_api/ में और tests tests/ में रखें।
- FastAPI से POST /tasks और GET /tasks बनाएं।
- pytest से happy path और 404 case test करें।
- ruff check और ruff format pass होने चाहिए।
- Edit करने से पहले plan दें, edit के बाद चलाए गए commands report करें।
Allowed files:
- pyproject.toml
- src/task_api/**
- tests/**
यह prompt Claude Code को सिर्फ code generator नहीं रहने देता। वह plan, implementation और verification के साथ काम करता है। अगर वह unrelated files बदलता है, तो review में तुरंत दिख जाएगा।
uv या venv से environment
नए learning project के लिए uv अच्छा default है, क्योंकि commands छोटे हैं और dependency sync तेज है। अगर company laptop पर tool install नहीं कर सकते, तो Python का standard venv भी ठीक है। बस दोनों को mix न करें।
macOS या Linux:
mkdir task-api
cd task-api
uv init --app --python 3.12
uv add "fastapi[standard]"
uv add --dev pytest ruff
mkdir -p src/task_api tests
touch src/task_api/__init__.py
Windows PowerShell:
mkdir task-api
cd task-api
uv init --app --python 3.12
uv add "fastapi[standard]"
uv add --dev pytest ruff
New-Item -ItemType Directory -Force src/task_api, tests
New-Item -ItemType File -Force src/task_api/__init__.py
uv न हो तो:
python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install "fastapi[standard]" pytest ruff
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install "fastapi[standard]" pytest ruff
pyproject.toml में rules रखें
Beginners के लिए अलग-अलग config files confusing हो सकती हैं। इसलिए dependencies, scripts, pytest path और Ruff rules एक जगह रखें।
[project]
name = "task-api"
version = "0.1.0"
description = "Small FastAPI and CLI sample for Claude Code practice"
requires-python = ">=3.11"
dependencies = [
"fastapi[standard]>=0.115.0",
]
[project.scripts]
task-api = "task_api.cli:main"
[dependency-groups]
dev = [
"pytest>=8.0.0",
"ruff>=0.8.0",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/task_api"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
[tool.ruff]
line-length = 100
target-version = "py311"
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]
FastAPI और CLI skeleton
src/task_api/main.py में यह code रखें। यह memory में data रखता है, इसलिए production storage नहीं है। सीखने के लिए यह अच्छा है क्योंकि routing, validation और error handling साफ दिखते हैं।
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(title="Task API")
class TaskCreate(BaseModel):
title: str = Field(min_length=1, max_length=80)
class Task(BaseModel):
id: int
title: str
done: bool = False
_tasks: dict[int, Task] = {}
_next_id = 1
@app.post("/tasks", response_model=Task, status_code=201)
def create_task(payload: TaskCreate) -> Task:
global _next_id
task = Task(id=_next_id, title=payload.title)
_tasks[task.id] = task
_next_id += 1
return task
@app.get("/tasks", response_model=list[Task])
def list_tasks() -> list[Task]:
return list(_tasks.values())
@app.patch("/tasks/{task_id}/done", response_model=Task)
def mark_done(task_id: int) -> Task:
task = _tasks.get(task_id)
if task is None:
raise HTTPException(status_code=404, detail="Task not found")
updated = task.model_copy(update={"done": True})
_tasks[task_id] = updated
return updated
uv run fastapi dev src/task_api/main.py
CLI चाहिए तो src/task_api/cli.py बनाएं।
import argparse
import json
from pathlib import Path
DB_PATH = Path("tasks.json")
def load_tasks() -> list[dict[str, object]]:
if not DB_PATH.exists():
return []
return json.loads(DB_PATH.read_text(encoding="utf-8"))
def save_tasks(tasks: list[dict[str, object]]) -> None:
DB_PATH.write_text(json.dumps(tasks, ensure_ascii=False, indent=2), encoding="utf-8")
def add_task(title: str) -> dict[str, object]:
tasks = load_tasks()
task = {"id": len(tasks) + 1, "title": title, "done": False}
tasks.append(task)
save_tasks(tasks)
return task
def main() -> None:
parser = argparse.ArgumentParser(description="Task CLI")
subparsers = parser.add_subparsers(dest="command", required=True)
add_parser = subparsers.add_parser("add")
add_parser.add_argument("title")
args = parser.parse_args()
if args.command == "add":
task = add_task(args.title)
print(f"Added #{task['id']}: {task['title']}")
if __name__ == "__main__":
main()
uv run task-api add "write pytest"
pytest और Ruff से safety
tests/test_main.py बनाएं। इसके बाद हर Claude Code change के बाद वही commands चलाएं।
import pytest
from fastapi.testclient import TestClient
from task_api import main
from task_api.main import app
@pytest.fixture(autouse=True)
def clean_tasks() -> None:
main._tasks.clear()
main._next_id = 1
def test_create_and_list_tasks() -> None:
client = TestClient(app)
response = client.post("/tasks", json={"title": "Write pytest"})
assert response.status_code == 201
assert response.json()["title"] == "Write pytest"
list_response = client.get("/tasks")
assert list_response.status_code == 200
assert len(list_response.json()) == 1
def test_mark_done_returns_404_for_missing_task() -> None:
client = TestClient(app)
response = client.patch("/tasks/999/done")
assert response.status_code == 404
assert response.json()["detail"] == "Task not found"
uv run pytest
uv run ruff check .
uv run ruff format .
वास्तविक उपयोग
पहला use case learning API है, जहां routing, Pydantic, OpenAPI docs, tests और formatting साथ में सीखते हैं। दूसरा use case business automation CLI है, जैसे CSV साफ करना, files rename करना या weekly report बनाना। तीसरा use case legacy Python scripts में tests जोड़ना है, ताकि refactor से पहले current behavior सुरक्षित हो। चौथा use case team training template है, जहां सभी लोग एक ही pyproject.toml, src layout और commands से शुरू करते हैं।
Individual learner Claude Code products से reusable prompts ले सकता है। Team rollout, review rules या production risk हो तो training और consultation ज्यादा सही next step है।
आम गलतियां
Package manager तय किए बिना prompt न दें, वरना pip, poetry, uv और requirements.txt mix हो सकते हैं। Database और JWT जल्दी न जोड़ें। src layout में import error से बचने के लिए pythonpath = ["src"] रखें। Ruff auto-fix का diff देखें। Prompt में secrets, customer data या production URLs कभी न डालें।
हाथ से जांचा गया परिणाम
इस update में Masa के beginner Python material वाला क्रम अपनाया गया: environment fix, pyproject.toml, छोटा FastAPI, tests, फिर Ruff। इससे हर failure environment, import, test behavior या formatting में अलग दिखता है। यही छोटा scaffold Claude Code को सीखने, training और real repository improvement के लिए भरोसेमंद बनाता है।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Obsidian to CLAUDE.md workflow: context बार-बार न समझाएं
Obsidian notes को CLAUDE.md operating notes में बदलकर Claude Code sessions को resume करना आसान बनाएं.
Claude Code Revenue CTA Routing: article से PDF, Gumroad और consultation तक
Reader intent के आधार पर free PDF, Gumroad products और consultation तक CTA route करने वाला workflow.
Claude Code टीम हैंडऑफ नियम: review proof, permissions, rollback और revenue path
Claude Code टीम काम के लिए evidence, permission rules, rollback, free PDF, Gumroad और consultation path वाला handoff.