🔧 Python Setup (pyenv/python3)
Before asking Claude Code to do anything in Python, you need a working Python setup. The most reliable way is to use pyenv to manage versions or the python3 built into the system. pyenv lets you keep multiple versions side by side and switch between them by project.
Claude Code can detect which version of Python is active and adapt the generated code. But if you don't have a clean setup, it will generate code for a version that may not exist on your machine. Start off right.
# Instalar pyenv (macOS/Linux) curl https://pyenv.run | bash # Instalar Python 3.12 pyenv install 3.12 # Definir como versao do projeto cd meu-projeto pyenv local 3.12 # Verificar python --version # Python 3.12.x
In one sentence: pyenv gives you the right Python version for each project, without conflicts.
📦 Virtual Environments (venv/uv)
A virtual environment is an isolated copy of Python for each project. Without it, packages from different projects conflict. The venv comes with Python; the uv is a modern and much faster alternative.
# Opcao 1: venv padrao python3 -m venv .venv source .venv/bin/activate # Opcao 2: uv (rapido) pip install uv uv venv .venv source .venv/bin/activate # Verificar que esta no venv which python # deve apontar para .venv/bin/python
Common mistake
Forgetting to activate the venv before running pip install. The package goes into the global Python environment and isn’t available in the project.
In one sentence: always create a .venv for each project; always activate it before installing packages.
📥 pip/uv for Dependencies
When Claude Code generates code that uses requests, fastapi or any other package, you need to install it. The pip is the default manager; uv pip does the same thing 10–100x faster. The file requirements.txt records exactly what was installed.
# Instalar um pacote pip install requests # Travar dependencias pip freeze > requirements.txt # Instalar de um requirements.txt pip install -r requirements.txt # Alternativa rapida com uv uv pip install -r requirements.txt
In one sentence: pip install + pip freeze = locked, reproducible dependencies.
📝 Basic Automation Scripts
The classic workflow with Claude Code: you describe what you want to automate, it generates the script, and you run and refine it. Start with small scripts that do ONE thing well. Use argparse for arguments, pathlib for paths and if __name__ == "__main__" as an entry point.
#!/usr/bin/env python3
"""Organiza arquivos por extensao em subpastas."""
import argparse
from pathlib import Path
def organize(directory: Path) -> None:
for f in directory.iterdir():
if f.is_file() and not f.name.startswith('.'):
ext_dir = directory / f.suffix.lstrip('.')
ext_dir.mkdir(exist_ok=True)
f.rename(ext_dir / f.name)
print(f" {f.name} -> {ext_dir.name}/")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("dir", type=Path)
args = parser.parse_args()
organize(args.dir)
In one sentence: small scripts + argparse + pathlib = clean automation Claude Code generates in seconds.
🐛 Debugging with Claude
When a script fails, paste the full traceback into Claude Code. It identifies the error, suggests a fix, and can apply it directly. For subtler bugs, use pdb (the native debugger) or breakpoint() to pause execution and inspect variables.
Debug workflow with Claude Code
1. Run the script and capture the error
2. Paste the complete traceback into Claude Code
3. Claude identifies the cause and applies the fix
4. Run It Again to Confirm
In one sentence: traceback + Claude Code = debugging in seconds, not hours.
🏷️ AI-Assisted Type Hints
Python is dynamic, but type hints make the code safer and easier for AI to understand. Ask Claude Code to add type hints to your existing code: "adicione type hints a todas as funcoes deste modulo". Use mypy to check.
from pathlib import Path
def count_lines(filepath: Path) -> int:
"""Conta linhas de um arquivo."""
return len(filepath.read_text().splitlines())
def process_files(directory: Path, ext: str = ".py") -> dict[str, int]:
"""Retorna {arquivo: n_linhas} para cada arquivo com a extensao."""
return {
f.name: count_lines(f)
for f in directory.glob(f"*{ext}")
}
In one sentence: type hints = clearer code for you, for AI, and for mypy.
🧾 Module Summary
Next module:
5.2 — Script Automation: scraping, file processing, and scheduling.