python-ultimate

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python 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 (
T | None
), never
Optional[T]
. Python 3.10+ required.
python
def process(data: str, limit: int | None = None) -> list[str]: ...
Never use
TYPE_CHECKING
guards.
See references/type-checking.md for alternatives.
所有场景强制使用类型提示。使用管道语法(
T | None
),禁止使用
Optional[T]
。要求Python 3.10及以上版本。
python
def process(data: str, limit: int | None = None) -> list[str]: ...
禁止使用
TYPE_CHECKING
防护
。替代方案请见references/type-checking.md

String Formatting

字符串格式化

Use f-strings only. No
.format()
or
%
formatting.
仅使用f-strings。禁止使用
.format()
%
格式化方式。

Code Size Limits

代码规模限制

TargetLimit
Module< 250 lines
Function< 75 lines
Class< 200 lines
目标限制
模块< 250行
函数< 75行
< 200行

Docstrings

文档字符串

Google style. Required for public functions and classes.
采用Google风格。公共函数和类必须编写文档字符串。

Prohibited Patterns

禁用模式

  • TYPE_CHECKING
    guards
  • os.path
    (use
    pathlib.Path
    )
  • Optional[T]
    (use
    T | None
    )
  • # noqa
    comments
  • sys.path
    manipulation
  • Defensive
    try/except ImportError
    for required dependencies (see references/imports-optional-dependencies.md)
  • Vague or wide parameter/return types with hidden
    isinstance
    /
    hasattr
    checks and
    None
    -as-error returns (see references/coding-standards.md)

  • TYPE_CHECKING
    防护
  • os.path
    (请使用
    pathlib.Path
  • Optional[T]
    (请使用
    T | None
  • # noqa
    注释
  • sys.path
    操作
  • 对必填依赖使用防御性
    try/except ImportError
    (详情请见references/imports-optional-dependencies.md
  • 使用模糊或宽泛的参数/返回类型,搭配隐藏的
    isinstance
    /
    hasattr
    检查和以
    None
    作为错误返回值(详情请见references/coding-standards.md

Naming Conventions

命名约定

Variable naming standards for clarity and consistency. See references/naming-conventions.md for full details.
为保证清晰性和一致性的变量命名标准。完整详情请见references/naming-conventions.md

Files and Directories

文件与目录

PatternSuffixExample
Files
_file
output_file
,
config_file
Directories
_dir
cache_dir
,
output_dir
Unknown type
_path
data_path
(exceptional only)
Anti-patterns (always invalid for path variables):
  • Bare generic names:
    path
    ,
    file
    ,
    folder
    ,
    dir
    ,
    directory
    ,
    output
    ,
    input
    ,
    source
    ,
    target
    ,
    dest
  • Prefix instead of suffix:
    dir_output
    ,
    file_config
  • Missing suffix:
    results
    ,
    data
    ,
    config
    (ambiguous)
See references/naming-conventions.md for the complete anti-pattern list.
模式后缀示例
文件
_file
output_file
,
config_file
目录
_dir
cache_dir
,
output_dir
未知类型
_path
data_path
(仅特殊情况使用)
反模式(路径变量绝对禁止使用):
  • 通用裸名:
    path
    ,
    file
    ,
    folder
    ,
    dir
    ,
    directory
    ,
    output
    ,
    input
    ,
    source
    ,
    target
    ,
    dest
  • 前缀而非后缀:
    dir_output
    ,
    file_config
  • 缺少后缀:
    results
    ,
    data
    ,
    config
    (含义模糊)
完整反模式列表请见references/naming-conventions.md

Test Naming

测试命名

  • Files:
    test_<module>.py
  • Classes:
    Test<DataProcessor>
    (PascalCase with Test prefix)
  • Methods:
    test_<description>
    (snake_case with test_ prefix)
  • 文件:
    test_<module>.py
  • 类:
    Test<DataProcessor>
    (PascalCase格式,以Test为前缀)
  • 方法:
    test_<description>
    (snake_case格式,以test_为前缀)

Automated Validation

自动化验证

bash
undefined
bash
undefined

Check 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

覆盖规则

RuleDescriptionQuick Fix
E402Module-level import not at topMove imports to top
B007Unused loop variablePrefix with
_
B008Function call in default argUse
None
sentinel
S108Hardcoded temp file pathUse
tempfile
PLC0415Import not at top-levelMove to module level
NPY002Legacy numpy randomUse
numpy.random
S311Standard randomUse
secrets
for security
规则描述快速修复
E402模块级导入未放在顶部将移至顶部
B007未使用的循环变量
_
为前缀
B008默认参数中的函数调用使用
None
标记
S108硬编码临时文件路径使用
tempfile
PLC0415导入未放在顶层移至模块级别
NPY002旧版numpy随机方法使用
numpy.random
S311标准随机方法安全场景使用
secrets

Typer Exception

Typer例外情况

B008 is allowed for Typer
Annotated
parameters. See references/linter-rules.md.

Typer的
Annotated
参数允许使用B008规则。详情请见references/linter-rules.md

Testing

测试

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-missing
bash
uv run pytest -v --tb=short
uv run pytest --cov=src --cov-report=term-missing

Key Practices

核心实践

  • Co-located tests:
    <module>_test.py
    alongside implementation
  • 90%+ coverage target
  • Fixtures in
    conftest.py
  • Parameterized testing for multiple inputs
  • unittest.mock
    for external dependencies
  • 测试与实现代码同目录:
    <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阶段流程

  1. Root Cause — Reproduce, isolate, trace data flow
  2. Pattern Analysis — Identify state changes, timing issues
  3. Hypothesis — Form testable prediction
  4. Implementation — Minimal fix, verify with test
  1. 根本原因 — 复现问题、隔离范围、追踪数据流
  2. 模式分析 — 识别状态变化、时序问题
  3. 假设验证 — 形成可测试的预测
  4. 实现修复 — 最小化修复,用测试验证

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

工作流

  1. Find — Grep for target pattern
  2. Replace — Edit with
    replace_all
    for bulk changes
  3. Verify — Run tests, check for regressions
  1. 查找 — 使用Grep定位目标模式
  2. 替换 — 使用
    replace_all
    进行批量修改
  3. 验证 — 运行测试,检查回归问题

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

分析维度

  1. Architecture — Structure, modularity, dependencies
  2. Quality — Readability, complexity, duplication
  3. Security — Input validation, secrets, injection
  4. Performance — Bottlenecks, memory, I/O
  5. Testing — Coverage, quality, edge cases
  6. Maintainability — Documentation, technical debt
  1. 架构 — 结构、模块化、依赖关系
  2. 质量 — 可读性、复杂度、代码重复
  3. 安全 — 输入验证、密钥管理、注入风险
  4. 性能 — 瓶颈、内存占用、I/O操作
  5. 测试 — 覆盖率、测试质量、边缘场景
  6. 可维护性 — 文档、技术债务

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

导入顺序

  1. Standard library
  2. Third-party
  3. Local (absolute imports)

  1. 标准库
  2. 第三方库
  3. 本地模块(绝对导入)

File Analysis

文件分析

Non-destructive file and codebase analysis. See references/file-analysis.md.
非破坏性的文件和代码库分析。详情请见references/file-analysis.md

Tools

工具

  • stat
    for metadata
  • wc
    for line counts
  • Grep for pattern searching
  • Glob for file discovery

  • stat
    用于元数据获取
  • wc
    用于行数统计
  • Grep 用于模式搜索
  • Glob 用于文件发现

Type Checking Alternatives

类型检查替代方案

Never use
TYPE_CHECKING
guards. See references/type-checking.md.
禁止使用
TYPE_CHECKING
防护。详情请见references/type-checking.md

Alternatives

替代方案

  1. Extract shared types to dedicated modules
  2. Use protocols for structural typing
  3. Forward references (string literals)
  4. Local imports (last resort)

  1. 将共享类型提取到专用模块
  2. 使用协议进行结构类型检查
  3. 前向引用(字符串字面量)
  4. 本地导入(最后手段)

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:
  1. Analyze locally — Use metadata operations (file counts, grep patterns)
  2. Process locally — Execute all transformations in Python
  3. Return summary — Report counts, not full data
Example patterns:
python
undefined
针对10个及以上文件的高效Python执行方案。与迭代方式相比,可节省90-99%的token
适用场景:
  • 批量操作(10个及以上文件)
  • 复杂多步骤工作流
  • 跨大量文件的迭代处理
  • 用户提及效率/性能需求
工作流模式:
  1. 本地分析 — 使用元数据操作(文件计数、Grep模式)
  2. 本地处理 — 在Python中执行所有转换
  3. 返回摘要** — 报告计数,而非完整数据
示例模式:
python
undefined

Bulk 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}

```python
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}

```python

Code 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
references/
. Load only what you need:
FileContent
coding-standards.md
Type hints, formatting, size limits, docstrings, comments
cli-development.md
Typer/Click, parameters, Rich output, env vars
linter-rules.md
Ruff rules E402, B007, B008, S108, PLC0415, NPY002, S311
testing.md
Fixtures, parameterized, mocking, TDD, coverage
type-checking.md
TYPE_CHECKING alternatives, protocols, forward refs
debugging.md
4-phase process, red flags, rationalizations
refactoring.md
Bulk operations, code transfer, safety checks
code-review.md
Receiving feedback, push back, evaluation
auditing.md
6-dimension analysis, severity ratings
documentation.md
10-section structure, Mermaid diagrams
planning.md
PLAN.md template and example
file-analysis.md
Metadata, line counting, pattern searching
project-setup.md
Project structure, uv, imports
verification.md
Pre-commit hooks, tox, Makefile targets
imports-optional-dependencies.md
Required vs optional dependency import patterns
所有详细内容均位于
references/
目录下。按需加载即可:
文件内容
coding-standards.md
类型提示、格式化、规模限制、文档字符串、注释
cli-development.md
Typer/Click、参数、Rich输出、环境变量
linter-rules.md
Ruff规则E402、B007、B008、S108、PLC0415、NPY002、S311
testing.md
夹具、参数化测试、Mock、TDD、覆盖率
type-checking.md
TYPE_CHECKING替代方案、协议、前向引用
debugging.md
4阶段流程、危险信号、合理化分析
refactoring.md
批量操作、代码迁移、安全检查
code-review.md
接收反馈、反驳、评估
auditing.md
6维度分析、严重程度评级
documentation.md
10部分结构、Mermaid图表
planning.md
PLAN.md模板及示例
file-analysis.md
元数据、行数统计、模式搜索
project-setup.md
项目结构、uv、导入规范
verification.md
预提交钩子、tox、Makefile目标
imports-optional-dependencies.md
必填与可选依赖的导入模式