python

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python 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
    Any
    unless necessary
  • Imports: Avoid barrel exports in
    __init__.py
    ; prefer blank files
  • 命名规范:变量、方法和类使用描述性且简洁的名称
  • 文档要求:所有类、函数、枚举及枚举值都需添加文档字符串(Docstrings)
  • 类型提示:保持一致使用;除非必要,避免使用
    Any
  • 导入规则
    __init__.py
    中避免桶式导出(barrel exports);优先使用空文件

Type Annotations

类型注解

  • Use
    dict
    ,
    list
    instead of
    typing.Dict
    ,
    typing.List
  • Use
    str | None
    instead of
    Optional[str]
  • Include
    from __future__ import annotations
    at top of files with type hints
  • Prefer built-in types over typing module equivalents
  • 使用
    dict
    list
    而非
    typing.Dict
    typing.List
  • 使用
    str | None
    而非
    Optional[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
    environment.py
    file with individual methods per variable (e.g.,
    api_key()
    for
    API_KEY
    ,
    database_url()
    for
    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
    src/
    directory structure
  • Test methods start with
    test_
  • Use test class suites: for
    def foo()
    create
    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
    pytest
    over
    unittest
  • Use
    pytest-mock
    for mocking
  • Use
    conftest.py
    for shared fixtures
  • Use
    tests/__test_<package_name>__
    for shared testing code
  • 优先使用
    pytest
    而非
    unittest
  • 使用
    pytest-mock
    进行模拟操作
  • 使用
    conftest.py
    定义共享夹具(fixtures)
  • 使用
    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