python-code-style
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython Code Style & Documentation
Python代码风格与文档规范
Consistent code style and clear documentation make codebases maintainable and collaborative. This skill covers modern Python tooling, naming conventions, and documentation standards.
一致的代码风格和清晰的文档能让代码库更易于维护和协作。本技能涵盖现代Python工具、命名规范及文档标准。
When to Use This Skill
适用场景
- Setting up linting and formatting for a new project
- Writing or reviewing docstrings
- Establishing team coding standards
- Configuring ruff, mypy, or pyright
- Reviewing code for style consistency
- Creating project documentation
- 为新项目配置代码检查与格式化工具
- 编写或评审文档字符串
- 制定团队编码标准
- 配置ruff、mypy或pyright
- 评审代码风格一致性
- 创建项目文档
Core Concepts
核心概念
1. Automated Formatting
1. 自动化格式化
Let tools handle formatting debates. Configure once, enforce automatically.
让工具处理格式争议。一次配置,自动强制执行。
2. Consistent Naming
2. 一致的命名规范
Follow PEP 8 conventions with meaningful, descriptive names.
遵循PEP 8规范,使用有意义、描述性的名称。
3. Documentation as Code
3. 文档即代码
Docstrings should be maintained alongside the code they describe.
文档字符串应与其描述的代码同步维护。
4. Type Annotations
4. 类型注解
Modern Python code should include type hints for all public APIs.
现代Python代码应为所有公共API添加类型提示。
Quick Start
快速开始
bash
undefinedbash
undefinedInstall modern tooling
安装现代工具
pip install ruff mypy
pip install ruff mypy
Configure in pyproject.toml
在pyproject.toml中配置
[tool.ruff]
line-length = 120
target-version = "py312" # Adjust based on your project's minimum Python version
[tool.mypy]
strict = true
undefined[tool.ruff]
line-length = 120
target-version = "py312" # 根据项目最低Python版本调整
[tool.mypy]
strict = true
undefinedFundamental Patterns
基础实践模式
Pattern 1: Modern Python Tooling
模式1:现代Python工具链
Use as an all-in-one linter and formatter. It replaces flake8, isort, and black with a single fast tool.
rufftoml
undefined使用作为集代码检查与格式化为一体的工具。它可替代flake8、isort和black,是一款高效的单一工具。
rufftoml
undefinedpyproject.toml
pyproject.toml
[tool.ruff]
line-length = 120
target-version = "py312" # Adjust based on your project's minimum Python version
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"UP", # pyupgrade
"SIM", # flake8-simplify
]
ignore = ["E501"] # Line length handled by formatter
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
Run with:
```bash
ruff check --fix . # Lint and auto-fix
ruff format . # Format code[tool.ruff]
line-length = 120
target-version = "py312" # 根据项目最低Python版本调整
[tool.ruff.lint]
select = [
"E", # pycodestyle错误
"W", # pycodestyle警告
"F", # pyflakes
"I", # isort
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"UP", # pyupgrade
"SIM", # flake8-simplify
]
ignore = ["E501"] # 由格式化工具处理行长度
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
运行命令:
```bash
ruff check --fix . # 代码检查并自动修复
ruff format . # 格式化代码Pattern 2: Type Checking Configuration
模式2:类型检查配置
Configure strict type checking for production code.
toml
undefined为生产代码配置严格的类型检查。
toml
undefinedpyproject.toml
pyproject.toml
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_ignores = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
[[tool.mypy.overrides]]
module = "tests.*"
disallow_untyped_defs = false
Alternative: Use `pyright` for faster checking.
```toml
[tool.pyright]
pythonVersion = "3.12"
typeCheckingMode = "strict"[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_ignores = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
[[tool.mypy.overrides]]
module = "tests.*"
disallow_untyped_defs = false
替代方案:使用`pyright`进行更快的检查。
```toml
[tool.pyright]
pythonVersion = "3.12"
typeCheckingMode = "strict"Pattern 3: Naming Conventions
模式3:命名规范
Follow PEP 8 with emphasis on clarity over brevity.
Files and Modules:
python
undefined遵循PEP 8规范,强调清晰性而非简洁性。
文件与模块:
python
undefinedGood: Descriptive snake_case
推荐:描述性蛇形命名法
user_repository.py
order_processing.py
http_client.py
user_repository.py
order_processing.py
http_client.py
Avoid: Abbreviations
避免:缩写
usr_repo.py
ord_proc.py
http_cli.py
**Classes and Functions:**
```pythonusr_repo.py
ord_proc.py
http_cli.py
**类与函数:**
```pythonClasses: PascalCase
类:大驼峰命名法
class UserRepository:
pass
class HTTPClientFactory: # Acronyms stay uppercase
pass
class UserRepository:
pass
class HTTPClientFactory: # 首字母缩略词保持大写
pass
Functions and variables: snake_case
函数与变量:蛇形命名法
def get_user_by_email(email: str) -> User | None:
retry_count = 3
max_connections = 100
**Constants:**
```pythondef get_user_by_email(email: str) -> User | None:
retry_count = 3
max_connections = 100
**常量:**
```pythonModule-level constants: SCREAMING_SNAKE_CASE
模块级常量:全大写蛇形命名法
MAX_RETRY_ATTEMPTS = 3
DEFAULT_TIMEOUT_SECONDS = 30
API_BASE_URL = "https://api.example.com"
undefinedMAX_RETRY_ATTEMPTS = 3
DEFAULT_TIMEOUT_SECONDS = 30
API_BASE_URL = "https://api.example.com"
undefinedPattern 4: Import Organization
模式4:导入组织
Group imports in a consistent order: standard library, third-party, local.
python
undefined按以下固定顺序分组导入:标准库、第三方库、本地模块。
python
undefinedStandard library
标准库
import os
from collections.abc import Callable
from typing import Any
import os
from collections.abc import Callable
from typing import Any
Third-party packages
第三方包
import httpx
from pydantic import BaseModel
from sqlalchemy import Column
import httpx
from pydantic import BaseModel
from sqlalchemy import Column
Local imports
本地导入
from myproject.models import User
from myproject.services import UserService
Use absolute imports exclusively:
```pythonfrom myproject.models import User
from myproject.services import UserService
仅使用绝对导入:
```pythonPreferred
推荐
from myproject.utils import retry_decorator
from myproject.utils import retry_decorator
Avoid relative imports
避免相对导入
from ..utils import retry_decorator
undefinedfrom ..utils import retry_decorator
undefinedAdvanced Patterns
进阶实践模式
Pattern 5: Google-Style Docstrings
模式5:Google风格文档字符串
Write docstrings for all public classes, methods, and functions.
Simple Function:
python
def get_user(user_id: str) -> User:
"""Retrieve a user by their unique identifier."""
...Complex Function:
python
def process_batch(
items: list[Item],
max_workers: int = 4,
on_progress: Callable[[int, int], None] | None = None,
) -> BatchResult:
"""Process items concurrently using a worker pool.
Processes each item in the batch using the configured number of
workers. Progress can be monitored via the optional callback.
Args:
items: The items to process. Must not be empty.
max_workers: Maximum concurrent workers. Defaults to 4.
on_progress: Optional callback receiving (completed, total) counts.
Returns:
BatchResult containing succeeded items and any failures with
their associated exceptions.
Raises:
ValueError: If items is empty.
ProcessingError: If the batch cannot be processed.
Example:
>>> result = process_batch(items, max_workers=8)
>>> print(f"Processed {len(result.succeeded)} items")
"""
...Class Docstring:
python
class UserService:
"""Service for managing user operations.
Provides methods for creating, retrieving, updating, and
deleting users with proper validation and error handling.
Attributes:
repository: The data access layer for user persistence.
logger: Logger instance for operation tracking.
Example:
>>> service = UserService(repository, logger)
>>> user = service.create_user(CreateUserInput(...))
"""
def __init__(self, repository: UserRepository, logger: Logger) -> None:
"""Initialize the user service.
Args:
repository: Data access layer for users.
logger: Logger for tracking operations.
"""
self.repository = repository
self.logger = logger为所有公共类、方法和函数编写文档字符串。
简单函数:
python
def get_user(user_id: str) -> User:
"""通过唯一标识符获取用户。"""
...复杂函数:
python
def process_batch(
items: list[Item],
max_workers: int = 4,
on_progress: Callable[[int, int], None] | None = None,
) -> BatchResult:
"""使用工作池并发处理项目。
配置指定数量的工作线程并发处理批量项目。可通过可选回调函数监控进度。
参数:
items: 待处理的项目列表,不能为空。
max_workers: 最大并发工作线程数,默认值为4。
on_progress: 可选回调函数,接收(已完成数, 总数)作为参数。
返回:
包含成功处理项目和失败项目(含关联异常)的BatchResult对象。
异常:
ValueError: 当items为空时抛出。
ProcessingError: 当批量处理无法执行时抛出。
示例:
>>> result = process_batch(items, max_workers=8)
>>> print(f"已处理 {len(result.succeeded)} 个项目")
"""
...类文档字符串:
python
class UserService:
"""用户操作管理服务。
提供用户创建、查询、更新和删除的方法,并包含完善的验证和错误处理机制。
属性:
repository: 用户持久化的数据访问层。
logger: 用于操作追踪的日志实例。
示例:
>>> service = UserService(repository, logger)
>>> user = service.create_user(CreateUserInput(...))
"""
def __init__(self, repository: UserRepository, logger: Logger) -> None:
"""初始化用户服务。
参数:
repository: 用户数据访问层。
logger: 用于操作追踪的日志实例。
"""
self.repository = repository
self.logger = loggerPattern 6: Line Length and Formatting
模式6:行长度与格式化
Set line length to 120 characters for modern displays while maintaining readability.
python
undefined将行长度设置为120字符(适配现代显示器),同时保持可读性。
python
undefinedGood: Readable line breaks
推荐:可读性强的换行
def create_user(
email: str,
name: str,
role: UserRole = UserRole.MEMBER,
notify: bool = True,
) -> User:
...
def create_user(
email: str,
name: str,
role: UserRole = UserRole.MEMBER,
notify: bool = True,
) -> User:
...
Good: Chain method calls clearly
推荐:清晰的链式方法调用
result = (
db.query(User)
.filter(User.active == True)
.order_by(User.created_at.desc())
.limit(10)
.all()
)
result = (
db.query(User)
.filter(User.active == True)
.order_by(User.created_at.desc())
.limit(10)
.all()
)
Good: Format long strings
推荐:长字符串格式化
error_message = (
f"Failed to process user {user_id}: "
f"received status {response.status_code} "
f"with body {response.text[:100]}"
)
undefinederror_message = (
f"处理用户 {user_id} 失败:"
f"收到状态码 {response.status_code} "
f"响应体:{response.text[:100]}"
)
undefinedPattern 7: Project Documentation
模式7:项目文档
README Structure:
markdown
undefinedREADME结构:
markdown
undefinedProject Name
项目名称
Brief description of what the project does.
项目功能简介。
Installation
安装
```bash
pip install myproject
```
```bash
pip install myproject
```
Quick Start
快速开始
```python
from myproject import Client
client = Client(api_key="...")
result = client.process(data)
```
```python
from myproject import Client
client = Client(api_key="...")
result = client.process(data)
```
Configuration
配置
Document environment variables and configuration options.
记录环境变量和配置选项。
Development
开发
```bash
pip install -e ".[dev]"
pytest
```
**CHANGELOG Format (Keep a Changelog):**
```markdown```bash
pip install -e ".[dev]"
pytest
```
**CHANGELOG格式(遵循Keep a Changelog规范):**
```markdownChangelog
更新日志
[Unreleased]
[未发布]
Added
新增
- New feature X
- 新功能X
Changed
变更
- Modified behavior of Y
- 修改Y的行为
Fixed
修复
- Bug in Z
undefined- Z中的Bug
undefinedBest Practices Summary
最佳实践总结
- Use ruff - Single tool for linting and formatting
- Enable strict mypy - Catch type errors before runtime
- 120 character lines - Modern standard for readability
- Descriptive names - Clarity over brevity
- Absolute imports - More maintainable than relative
- Google-style docstrings - Consistent, readable documentation
- Document public APIs - Every public function needs a docstring
- Keep docs updated - Treat documentation as code
- Automate in CI - Run linters on every commit
- Target Python 3.10+ - For new projects, Python 3.12+ is recommended for modern language features
- 使用ruff - 集代码检查与格式化为一体的单一工具
- 启用严格的mypy - 在运行前捕获类型错误
- 120字符行长度 - 现代可读性标准
- 描述性命名 - 清晰优先于简洁
- 绝对导入 - 比相对导入更易于维护
- Google风格文档字符串 - 一致、易读的文档
- 文档化公共API - 每个公共函数都需要文档字符串
- 保持文档更新 - 将文档视为代码的一部分
- 在CI中自动化 - 每次提交都运行代码检查工具
- 目标Python 3.10+ - 新项目推荐使用Python 3.12+以支持现代语言特性