python
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython Guidelines
Python开发指南
Standards and best practices for Python development. Follow these guidelines when writing or modifying Python code.
Python开发的标准与最佳实践。编写或修改Python代码时请遵循本指南。
Design Principles
设计原则
Apply DRY, KISS, and SOLID consistently. Prefer functional methods where relevant; use classes for stateful behavior. Use composition with Protocol classes for interfaces rather than inheritance. Each module should have a single responsibility. Use dependency injection for class dependencies.
始终遵循DRY、KISS和SOLID原则。相关场景下优先使用函数式方法;有状态行为使用类实现。使用Protocol类进行组合来定义接口,而非继承。每个模块应具备单一职责。类的依赖项使用依赖注入。
Code Style
代码风格
- Naming: Descriptive yet concise names for variables, methods, and classes
- Documentation: Docstrings for all classes, functions, enums, enum values
- Type hints: Use consistently; avoid unless necessary
Any - Imports: Avoid barrel exports in ; prefer blank files
__init__.py
- 命名规范:变量、方法和类使用描述性且简洁的名称
- 文档要求:所有类、函数、枚举及枚举值都需添加文档字符串(Docstrings)
- 类型提示:保持一致使用;除非必要,避免使用
Any - 导入规则:中避免桶式导出(barrel exports);优先使用空文件
__init__.py
Type Annotations
类型注解
- Use ,
dictinstead oflist,typing.Dicttyping.List - Use instead of
str | NoneOptional[str] - Include at top of files with type hints
from __future__ import annotations - Prefer built-in types over typing module equivalents
- 使用、
dict而非list、typing.Dicttyping.List - 使用而非
str | NoneOptional[str] - 带有类型注解的文件顶部需包含
from __future__ import annotations - 优先使用内置类型而非typing模块中的等效类型
Architecture
架构设计
Dependency Injection
依赖注入
- Always inject dependencies via constructors or methods when using classes
- One service class per module (interface and class models allowed in addition)
- Use Protocol classes to define interfaces for dependency injection and testing
- 使用类时,始终通过构造函数或方法注入依赖项
- 每个模块对应一个服务类(允许额外包含接口和类模型)
- 使用Protocol类定义依赖注入和测试所需的接口
Module Organization
模块组织
- Each module focuses on one concern with clear boundaries
- Extract reusable methods to avoid duplication
- Design for reusability across contexts
- 每个模块聚焦单一关注点,边界清晰
- 提取可复用方法以避免重复代码
- 设计时考虑跨场景的复用性
Environment Variables
环境变量
- Use an file with individual methods per variable (e.g.,
environment.pyforapi_key(),API_KEYfordatabase_url())DATABASE_URL - Co-locate all environment access in one place per package for easier mocking in tests
- 使用文件,每个环境变量对应单独方法(例如,
environment.py对应api_key(),API_KEY对应database_url())DATABASE_URL - 每个包的所有环境变量访问逻辑集中存放一处,便于测试时进行模拟
Data Models
数据模型
- Use Pydantic v2 for schemas, validation, and data models
- Leverage Pydantic's type validation, serialization, and configuration management
- Use Pydantic models for API request/response schemas, configuration objects, and data transfer objects
- 使用Pydantic v2定义 schema、验证规则和数据模型
- 利用Pydantic的类型验证、序列化和配置管理功能
- 将Pydantic模型用于API请求/响应schema、配置对象和数据传输对象
Testing
测试
Structure
结构规范
- Tests mirror directory structure
src/ - Test methods start with
test_ - Use test class suites: for create
def foo()class TestFoo - Keep names concise, omit class suite name from method
- Always check for appropriate unit tests when changing code
- 测试目录结构与目录结构保持一致
src/ - 测试方法以开头
test_ - 使用测试类套件:例如为创建
def foo()class TestFoo - 名称保持简洁,方法名中省略类套件名称
- 修改代码时,务必检查是否存在对应的单元测试
Quality
测试质量
- Use AAA (Arrange, Act, Assert) pattern
- Tests should be useful, readable, concise, maintainable
- Avoid tests that create massive diffs or become burdensome
- 遵循AAA(Arrange、Act、Assert)模式
- 测试用例应实用、可读、简洁且易于维护
- 避免会产生大量差异或维护成本过高的测试
Tools
工具选择
- Prefer over
pytestunittest - Use for mocking
pytest-mock - Use for shared fixtures
conftest.py - Use for shared testing code
tests/__test_<package_name>__
- 优先使用而非
pytestunittest - 使用进行模拟操作
pytest-mock - 使用定义共享夹具(fixtures)
conftest.py - 使用存放共享测试代码
tests/__test_<package_name>__
Implementation
实施要求
When implementing Python code:
- Ensure code passes type checking and tests before committing
- Group related changes with tests in atomic commits
- Check for existing workflow patterns (spec-first, TDD, etc.) and follow them
编写Python代码时:
- 提交前确保代码通过类型检查和测试
- 相关修改与对应测试分组为原子提交
- 检查现有工作流模式(如先写规格、测试驱动开发TDD等)并遵循执行
References
参考资料
- For adhoc Python scripts in uv-managed projects, see .
references/uv-scripts.md - For monorepo-specific patterns using uv and Hatch, see .
references/uv-monorepo.md
- 关于uv管理项目中的临时Python脚本,请参考。
references/uv-scripts.md - 关于使用uv和Hatch的单仓库(monorepo)特定模式,请参考。
references/uv-monorepo.md