python-ultimate
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython Ultimate
Python 全能开发参考手册
Complete Python development reference. Covers standards, tooling, workflows, and best practices.
完整的Python开发参考资料,涵盖编码标准、工具使用、工作流程及最佳实践。
Quick Start
快速入门
Writing code? → Start with Coding Standards
Checking naming? → Go to Naming Conventions
Building a CLI? → Go to CLI Development
Fixing linter errors? → Go to Linter Rules
Writing tests? → Go to Testing
Debugging a bug? → Go to Debugging
Refactoring? → Go to Refactoring
Reviewing code? → Go to Code Review
Auditing codebase? → Go to Auditing
Documenting? → Go to Documentation
Planning a feature? → Go to Planning
Bulk operations? → Go to Bulk Operations (10+ files, 90%+ token savings)
编写代码? → 从编码标准开始
检查命名规范? → 查看命名约定
构建CLI工具? → 查看CLI开发
修复代码检查错误? → 查看代码检查规则
编写测试用例? → 查看测试
调试Bug? → 查看调试
代码重构? → 查看重构
代码评审? → 查看代码评审
代码库审计? → 查看审计
编写文档? → 查看文档编写
功能规划? → 查看规划
批量操作? → 查看批量操作(10个及以上文件,节省90%+ token)
Coding Standards
编码标准
Core Python coding rules. See references/coding-standards.md for full details.
核心Python编码规则。完整详情请见references/coding-standards.md。
Type Hints
类型提示
Mandatory everywhere. Use pipe syntax (), never . Python 3.10+ required.
T | NoneOptional[T]python
def process(data: str, limit: int | None = None) -> list[str]: ...Never use guards. See references/type-checking.md for alternatives.
TYPE_CHECKING所有场景强制使用类型提示。使用管道语法(),禁止使用。要求Python 3.10及以上版本。
T | NoneOptional[T]python
def process(data: str, limit: int | None = None) -> list[str]: ...禁止使用防护。替代方案请见references/type-checking.md。
TYPE_CHECKINGString Formatting
字符串格式化
Use f-strings only. No or formatting.
.format()%仅使用f-strings。禁止使用或格式化方式。
.format()%Code Size Limits
代码规模限制
| Target | Limit |
|---|---|
| Module | < 250 lines |
| Function | < 75 lines |
| Class | < 200 lines |
| 目标 | 限制 |
|---|---|
| 模块 | < 250行 |
| 函数 | < 75行 |
| 类 | < 200行 |
Docstrings
文档字符串
Google style. Required for public functions and classes.
采用Google风格。公共函数和类必须编写文档字符串。
Prohibited Patterns
禁用模式
- guards
TYPE_CHECKING - (use
os.path)pathlib.Path - (use
Optional[T])T | None - comments
# noqa - manipulation
sys.path - Defensive for required dependencies (see references/imports-optional-dependencies.md)
try/except ImportError - Vague or wide parameter/return types with hidden /
isinstancechecks andhasattr-as-error returns (see references/coding-standards.md)None
- 防护
TYPE_CHECKING - (请使用
os.path)pathlib.Path - (请使用
Optional[T])T | None - 注释
# noqa - 操作
sys.path - 对必填依赖使用防御性(详情请见references/imports-optional-dependencies.md)
try/except ImportError - 使用模糊或宽泛的参数/返回类型,搭配隐藏的/
isinstance检查和以hasattr作为错误返回值(详情请见references/coding-standards.md)None
Naming Conventions
命名约定
Variable naming standards for clarity and consistency. See references/naming-conventions.md for full details.
为保证清晰性和一致性的变量命名标准。完整详情请见references/naming-conventions.md。
Files and Directories
文件与目录
| Pattern | Suffix | Example |
|---|---|---|
| Files | | |
| Directories | | |
| Unknown type | | |
Anti-patterns (always invalid for path variables):
- Bare generic names: ,
path,file,folder,dir,directory,output,input,source,targetdest - Prefix instead of suffix: ,
dir_outputfile_config - Missing suffix: ,
results,data(ambiguous)config
See references/naming-conventions.md for the complete anti-pattern list.
| 模式 | 后缀 | 示例 |
|---|---|---|
| 文件 | | |
| 目录 | | |
| 未知类型 | | |
反模式(路径变量绝对禁止使用):
- 通用裸名:,
path,file,folder,dir,directory,output,input,source,targetdest - 前缀而非后缀:,
dir_outputfile_config - 缺少后缀:,
results,data(含义模糊)config
完整反模式列表请见references/naming-conventions.md。
Test Naming
测试命名
- Files:
test_<module>.py - Classes: (PascalCase with Test prefix)
Test<DataProcessor> - Methods: (snake_case with test_ prefix)
test_<description>
- 文件:
test_<module>.py - 类:(PascalCase格式,以Test为前缀)
Test<DataProcessor> - 方法:(snake_case格式,以test_为前缀)
test_<description>
Automated Validation
自动化验证
bash
undefinedbash
undefinedCheck a variable name
检查变量名
uv run assets/check_path_naming.py output_file
uv run assets/check_path_naming.py output_file
Output: is_file
输出:is_file
Scan for violations
扫描违规情况
uv run assets/check_path_naming.py --check-files src/
______________________________________________________________________uv run assets/check_path_naming.py --check-files src/
______________________________________________________________________CLI Development
CLI开发
Building Python CLIs with Typer or Click. See references/cli-development.md.
使用Typer或Click构建Python CLI工具。详情请见references/cli-development.md。
Framework Selection
框架选择
Use Typer for new projects (type-hint driven, less boilerplate). Use Click for complex parameter handling.
新项目使用Typer(基于类型提示,更少样板代码)。复杂参数处理场景使用Click。
Key Patterns
核心模式
- Parameter validation with type hints
- Rich output formatting
- Environment variable integration
- Exit codes for error states
- 基于类型提示的参数验证
- 富文本输出格式化
- 环境变量集成
- 错误状态对应的退出码
Linter Rules
代码检查规则
Context-aware fixes for Ruff linter rules. See references/linter-rules.md.
针对Ruff代码检查工具规则的上下文感知修复方案。详情请见references/linter-rules.md。
Covered Rules
覆盖规则
| Rule | Description | Quick Fix |
|---|---|---|
| E402 | Module-level import not at top | Move imports to top |
| B007 | Unused loop variable | Prefix with |
| B008 | Function call in default arg | Use |
| S108 | Hardcoded temp file path | Use |
| PLC0415 | Import not at top-level | Move to module level |
| NPY002 | Legacy numpy random | Use |
| S311 | Standard random | Use |
| 规则 | 描述 | 快速修复 |
|---|---|---|
| E402 | 模块级导入未放在顶部 | 将移至顶部 |
| B007 | 未使用的循环变量 | 以 |
| B008 | 默认参数中的函数调用 | 使用 |
| S108 | 硬编码临时文件路径 | 使用 |
| PLC0415 | 导入未放在顶层 | 移至模块级别 |
| NPY002 | 旧版numpy随机方法 | 使用 |
| S311 | 标准随机方法 | 安全场景使用 |
Typer Exception
Typer例外情况
B008 is allowed for Typer parameters. See references/linter-rules.md.
AnnotatedTyper的参数允许使用B008规则。详情请见references/linter-rules.md。
AnnotatedTesting
测试
Test organization, fixtures, mocking, and TDD. See references/testing.md.
测试组织、夹具、Mock及测试驱动开发(TDD)。详情请见references/testing.md。
Quick Commands
快速命令
bash
uv run pytest -v --tb=short
uv run pytest --cov=src --cov-report=term-missingbash
uv run pytest -v --tb=short
uv run pytest --cov=src --cov-report=term-missingKey Practices
核心实践
- Co-located tests: alongside implementation
<module>_test.py - 90%+ coverage target
- Fixtures in
conftest.py - Parameterized testing for multiple inputs
- for external dependencies
unittest.mock
- 测试与实现代码同目录:与实现文件放在一起
<module>_test.py - 覆盖率目标90%+
- 夹具定义在中
conftest.py - 多输入场景使用参数化测试
- 外部依赖使用
unittest.mock
TDD Cycle
TDD循环
Red → Green → Refactor. No production code without a failing test first. See references/testing.md.
红 → 绿 → 重构。没有失败的测试用例,不编写生产代码。详情请见references/testing.md。
Debugging
调试
Systematic 4-phase debugging process. See references/debugging.md.
系统化的4阶段调试流程。详情请见references/debugging.md。
Iron Law
铁律
No fixes without root cause investigation first.
未找到根本原因,绝不修复问题。
4-Phase Process
4阶段流程
- Root Cause — Reproduce, isolate, trace data flow
- Pattern Analysis — Identify state changes, timing issues
- Hypothesis — Form testable prediction
- Implementation — Minimal fix, verify with test
- 根本原因 — 复现问题、隔离范围、追踪数据流
- 模式分析 — 识别状态变化、时序问题
- 假设验证 — 形成可测试的预测
- 实现修复 — 最小化修复,用测试验证
Red Flags
危险信号
- "Let me just try changing X"
- Fixing symptoms without understanding cause
- Multiple failed fix attempts
- “我先试试改X看看”
- 只修复症状,不理解原因
- 多次尝试修复均失败
Refactoring
重构
Find → Replace → Verify workflow. See references/refactoring.md.
查找 → 替换 → 验证工作流。详情请见references/refactoring.md。
Workflow
工作流
- Find — Grep for target pattern
- Replace — Edit with for bulk changes
replace_all - Verify — Run tests, check for regressions
- 查找 — 使用Grep定位目标模式
- 替换 — 使用进行批量修改
replace_all - 验证 — 运行测试,检查回归问题
Code Transfer
代码迁移
Line-based code movement between files. See references/refactoring.md.
基于行的跨文件代码移动。详情请见references/refactoring.md。
Code Review
代码评审
Receiving and evaluating code review feedback. See references/code-review.md.
接收和评估代码评审反馈。详情请见references/code-review.md。
Workflow
工作流
Read → Understand → Verify → Evaluate → Respond → Implement
阅读 → 理解 → 验证 → 评估 → 反馈 → 实现
Key Principles
核心原则
- No performative agreement
- Push back with technical reasoning
- Verify feedback before implementing
- Evaluate: is the suggestion correct?
- 不做形式上的同意
- 用技术理由反驳不合理反馈
- 实现前先验证反馈的正确性
- 评估:建议是否正确?
Auditing
审计
6-dimension codebase analysis. See references/auditing.md.
6维度代码库分析。详情请见references/auditing.md。
Dimensions
分析维度
- Architecture — Structure, modularity, dependencies
- Quality — Readability, complexity, duplication
- Security — Input validation, secrets, injection
- Performance — Bottlenecks, memory, I/O
- Testing — Coverage, quality, edge cases
- Maintainability — Documentation, technical debt
- 架构 — 结构、模块化、依赖关系
- 质量 — 可读性、复杂度、代码重复
- 安全 — 输入验证、密钥管理、注入风险
- 性能 — 瓶颈、内存占用、I/O操作
- 测试 — 覆盖率、测试质量、边缘场景
- 可维护性 — 文档、技术债务
Severity Ratings
严重程度评级
Critical → High → Medium → Low
Critical(严重)→ High(高)→ Medium(中)→ Low(低)
Documentation
文档编写
10-section documentation structure. See references/documentation.md.
10部分文档结构。详情请见references/documentation.md。
Workflow
工作流
Explore → Map → Read → Synthesize
探索 → 梳理 → 阅读 → 整合
Sections
文档章节
Project Overview, Architecture, Key Components, Data Flow, API Reference, Configuration, Setup Guide, Development Guide, Testing, Deployment
项目概述、架构、核心组件、数据流、API参考、配置说明、安装指南、开发指南、测试、部署
Mermaid Diagrams
Mermaid图表
Use for architecture, sequence, and flowchart visualizations.
用于架构、时序和流程图可视化。
Planning
规划
PLAN.md living document for feature implementation. See references/planning.md.
使用PLAN.md活文档进行功能实现规划。详情请见references/planning.md。
When to Use
使用场景
Features spanning 3-15 prompts. Self-contained for fresh sessions.
涉及3-15个提示词的功能。独立成篇,适用于新会话。
Structure
文档结构
Goal → Context → Phases → Validation → Progress → Decisions → Notes
目标 → 背景 → 阶段 → 验证 → 进度 → 决策 → 备注
Project Setup
项目搭建
Project structure, dependencies, and imports. See references/project-setup.md.
项目结构、依赖管理及导入规范。详情请见references/project-setup.md。
Key Tools
核心工具
- uv for dependency management
- src layout for packages
- pyproject.toml for configuration
- uv 用于依赖管理
- src布局 用于包结构
- pyproject.toml 用于配置
Import Order
导入顺序
- Standard library
- Third-party
- Local (absolute imports)
- 标准库
- 第三方库
- 本地模块(绝对导入)
File Analysis
文件分析
Non-destructive file and codebase analysis. See references/file-analysis.md.
非破坏性的文件和代码库分析。详情请见references/file-analysis.md。
Tools
工具
- for metadata
stat - for line counts
wc - Grep for pattern searching
- Glob for file discovery
- 用于元数据获取
stat - 用于行数统计
wc - Grep 用于模式搜索
- Glob 用于文件发现
Type Checking Alternatives
类型检查替代方案
Never use guards. See references/type-checking.md.
TYPE_CHECKING禁止使用防护。详情请见references/type-checking.md。
TYPE_CHECKINGAlternatives
替代方案
- Extract shared types to dedicated modules
- Use protocols for structural typing
- Forward references (string literals)
- Local imports (last resort)
- 将共享类型提取到专用模块
- 使用协议进行结构类型检查
- 前向引用(字符串字面量)
- 本地导入(最后手段)
Bulk Operations
批量操作
High-efficiency Python execution for 10+ file operations. 90-99% token savings vs. iterative approaches.
When to use:
- Bulk operations (10+ files)
- Complex multi-step workflows
- Iterative processing across many files
- User mentions efficiency/performance
Workflow pattern:
- Analyze locally — Use metadata operations (file counts, grep patterns)
- Process locally — Execute all transformations in Python
- Return summary — Report counts, not full data
Example patterns:
python
undefined针对10个及以上文件的高效Python执行方案。与迭代方式相比,可节省90-99%的token。
适用场景:
- 批量操作(10个及以上文件)
- 复杂多步骤工作流
- 跨大量文件的迭代处理
- 用户提及效率/性能需求
工作流模式:
- 本地分析 — 使用元数据操作(文件计数、Grep模式)
- 本地处理 — 在Python中执行所有转换
- 返回摘要** — 报告计数,而非完整数据
示例模式:
python
undefinedBulk refactor across 50 files
跨50个文件批量重构
from pathlib import Path
import re
files = list(Path('.').glob('**/*.py'))
modified = 0
for f in files:
content = f.read_text()
new_content = re.sub(r'old_pattern', 'new_pattern', content)
if new_content != content:
f.write_text(new_content)
modified += 1
result = {'files_scanned': len(files), 'files_modified': modified}
```pythonfrom pathlib import Path
import re
files = list(Path('.').glob('**/*.py'))
modified = 0
for f in files:
content = f.read_text()
new_content = re.sub(r'old_pattern', 'new_pattern', content)
if new_content != content:
f.write_text(new_content)
modified += 1
result = {'files_scanned': len(files), 'files_modified': modified}
```pythonCode audit metadata extraction
代码审计元数据提取
from pathlib import Path
import ast
files = list(Path('src').glob('**/*.py'))
complexity_issues = []
for f in files:
tree = ast.parse(f.read_text())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
# Calculate simple complexity metric
nested = sum(1 for n in ast.walk(node) if isinstance(n, (ast.If, ast.For, ast.While)))
if nested > 10:
complexity_issues.append({'file': str(f), 'function': node.name, 'complexity': nested})
result = {'files_audited': len(files), 'high_complexity': len(complexity_issues)}
**Best practices:**
- ✅ Return summaries, not full data
- ✅ Batch operations where possible
- ✅ Use `pathlib.Path` for file operations
- ✅ Handle errors gracefully, return error counts
- ❌ Don't read full source into context when metadata suffices
- ❌ Don't process files one-by-one interactively
**Token savings scale with file count:**
| Files | Interactive | Bulk Operation | Savings |
|-------|-------------|----------------|---------|
| 10 | ~5K tokens | ~500 tokens | 90% |
| 50 | ~25K tokens | ~600 tokens | 97.6% |
| 100 | ~150K tokens| ~1K tokens | 99.3% |
______________________________________________________________________from pathlib import Path
import ast
files = list(Path('src').glob('**/*.py'))
complexity_issues = []
for f in files:
tree = ast.parse(f.read_text())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
# 计算简单复杂度指标
nested = sum(1 for n in ast.walk(node) if isinstance(n, (ast.If, ast.For, ast.While)))
if nested > 10:
complexity_issues.append({'file': str(f), 'function': node.name, 'complexity': nested})
result = {'files_audited': len(files), 'high_complexity': len(complexity_issues)}
**最佳实践:**
- ✅ 返回摘要,而非完整数据
- ✅ 尽可能批量操作
- ✅ 使用`pathlib.Path`进行文件操作
- ✅ 优雅处理错误,返回错误计数
- ❌ 元数据足够时,不要将完整源码读入上下文
- ❌ 不要交互式逐个处理文件
**Token节省比例随文件数量增长:**
| 文件数量 | 交互式处理 | 批量操作 | 节省比例 |
|-------|-------------|----------------|---------|
| 10 | ~5K tokens | ~500 tokens | 90% |
| 50 | ~25K tokens | ~600 tokens | 97.6% |
| 100 | ~150K tokens| ~1K tokens | 99.3% |
______________________________________________________________________Reference Files
参考文件
All detailed content lives in . Load only what you need:
references/| File | Content |
|---|---|
| Type hints, formatting, size limits, docstrings, comments |
| Typer/Click, parameters, Rich output, env vars |
| Ruff rules E402, B007, B008, S108, PLC0415, NPY002, S311 |
| Fixtures, parameterized, mocking, TDD, coverage |
| TYPE_CHECKING alternatives, protocols, forward refs |
| 4-phase process, red flags, rationalizations |
| Bulk operations, code transfer, safety checks |
| Receiving feedback, push back, evaluation |
| 6-dimension analysis, severity ratings |
| 10-section structure, Mermaid diagrams |
| PLAN.md template and example |
| Metadata, line counting, pattern searching |
| Project structure, uv, imports |
| Pre-commit hooks, tox, Makefile targets |
| Required vs optional dependency import patterns |
所有详细内容均位于目录下。按需加载即可:
references/| 文件 | 内容 |
|---|---|
| 类型提示、格式化、规模限制、文档字符串、注释 |
| Typer/Click、参数、Rich输出、环境变量 |
| Ruff规则E402、B007、B008、S108、PLC0415、NPY002、S311 |
| 夹具、参数化测试、Mock、TDD、覆盖率 |
| TYPE_CHECKING替代方案、协议、前向引用 |
| 4阶段流程、危险信号、合理化分析 |
| 批量操作、代码迁移、安全检查 |
| 接收反馈、反驳、评估 |
| 6维度分析、严重程度评级 |
| 10部分结构、Mermaid图表 |
| PLAN.md模板及示例 |
| 元数据、行数统计、模式搜索 |
| 项目结构、uv、导入规范 |
| 预提交钩子、tox、Makefile目标 |
| 必填与可选依赖的导入模式 |