关于 coding-standards
面向 AI Agent 和大模型的 Python 编码规范集合,按性能、异步处理、设计、文档、验证和面向对象编程组织建议,并提供常见模式示例。
主要功能
- 01错误处理规则
- 02性能优化模式
- 03异步处理指南
- 04设计与 SOLID 原则
- 05文档和类型提示规范
适用场景
- 01指导 Python 代码生成
- 02检查 Python 实现模式
- 03采用异步资源管理实践
- 04统一公共 API 文档规范
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ ludo-technologies/ python-best-practices --skill coding-standards安装后在 Claude Code 中输入/coding-standards确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
metadata.jsonREADME.mdrules/_sections.md_template.mdasync-context-manager.mdasync-create-task.mdasync-gather.mdasync-semaphore.mddesign-dependency-injection.mddesign-early-return.mddesign-no-global-singleton.mddesign-philosophy.mddesign-pure-functions.mddesign-single-responsibility.mddoc-docstring.mddoc-type-hints.mderror-no-silent-exceptions.mdoop-composition-over-inheritance.mdoop-dataclass.mdoop-property.mdoop-protocol.mdperf-dict-get.mdperf-generator-expression.mdperf-list-comprehension.mdperf-set-lookup.mdperf-str-join.mdsolid-isp.mdsolid-lsp.mdsolid-ocp.mdvalidation-pydantic.md详细介绍
Python 编码规范
全面收集 Python 编码规范和最佳实践。旨在帮助 AI Agent 和大模型生成高质量、高性能且易于维护的 Python 代码。
分类
错误处理 [CRITICAL]
防止隐藏失败或将失败报告为成功结果。
| 规则 | 说明 |
|---|---|
| error-no-silent-exceptions | 绝不吞掉异常 |
性能优化 [CRITICAL]
应用 Python 优化模式,提升处理速度和内存效率。
| 规则 | 说明 |
|---|---|
| perf-list-comprehension | 优先使用列表推导式,而不是循环(速度快 1.5-2 倍) |
| perf-generator-expression | 对大型数据集使用生成器(内存占用为 O(1)) |
| perf-dict-get | 使用 dict.get() 高效获取默认值 |
| perf-set-lookup | 使用 set 加快查找速度(O(1),而非 O(n)) |
| perf-str-join | 使用 join 拼接字符串(O(n),而非 O(n²)) |
异步处理 [HIGH]
使用 asyncio 实现高效的异步编程模式。
| 规则 | 说明 |
|---|---|
| async-gather | 对独立任务使用 asyncio.gather |
| async-create-task | 正确创建后台任务 |
| async-context-manager | 使用 async with 管理资源 |
| async-semaphore | 使用信号量限制并发 |
设计原则 [HIGH]
提升可维护性和可扩展性的软件设计原则。
| 规则 | 说明 |
|---|---|
| design-philosophy | DRY、YAGNI、KISS 原则 |
| design-single-responsibility | 单一职责原则 |
| design-dependency-injection | 通过依赖注入实现松耦合 |
| design-no-global-singleton | 避免全局单例和模块级共享实例 |
| solid-ocp | 开闭原则 |
| solid-lsp | 里氏替换原则 |
| solid-isp | 接口隔离原则 |
| design-pure-functions | 优先使用无副作用的纯函数 |
| design-early-return | 通过提前返回减少嵌套 |
文档 [HIGH]
为公共 API 提供清晰的文档和可由机器检查的契约。
| 规则 | 说明 |
|---|---|
| doc-docstring | 使用 Google 风格的文档字符串记录公共 API |
| doc-type-hints | 要求公共 API 使用类型提示 |
数据验证 [HIGH]
验证跨越信任边界的数据。
| 规则 | 说明 |
|---|---|
| validation-pydantic | 使用 Pydantic 验证边界数据 |
面向对象编程 [MEDIUM]
Pythonic 面向对象编程的最佳实践。
| 规则 | 说明 |
|---|---|
| oop-composition-over-inheritance | 优先使用组合,而不是继承 |
| oop-dataclass | 使用 dataclass 作为数据容器 |
| oop-protocol | 优先使用 Protocol,而不是抽象基类 |
| oop-property | 使用 property 代替 getter |
快速参考
错误处理
try:
config = parse_config(path)
except ConfigParseError as exc:
raise StartupError(f"Invalid configuration: {path}") from exc
def main() -> int:
try:
start_application()
except StartupError:
logger.exception("Application startup failed")
return 1 # explicit non-success outcome at the process boundary
return 0
if __name__ == "__main__":
raise SystemExit(main())
性能模式
# List comprehension (not loops)
result = [x * 2 for x in items]
# Generator for large data
total = sum(x * x for x in range(1_000_000))
# dict.get() with default
value = config.get("key", default_value)
# Set for fast lookup
valid_ids: set[int] = {1, 2, 3}
if item_id in valid_ids: ...
# join for strings
result = ",".join(values)
异步模式
# Concurrent execution
results = await asyncio.gather(task1(), task2(), task3())
# Resource management
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.json()
# Concurrency limit
semaphore = asyncio.Semaphore(10)
async with semaphore:
await do_work()
设计模式
# Dependency injection (not module-level singletons)
class Service:
def __init__(self, repository: Repository) -> None:
self.repository = repository
# Composition root builds the graph once
def create_app(settings: Settings) -> Service:
return Service(repository=PostgresRepository(settings.dsn))
# Open/Closed: extend via new types, not edits
class JsonFormat:
def export(self, invoice: Invoice) -> str: ...
# Interface Segregation: small Protocols
class Workable(Protocol):
def work(self) -> None: ...
# Early return
def process(data: Data | None) -> Result:
if data is None:
return Result.empty()
# main logic here
文档模式
def create_user(email: str, name: str) -> User:
"""Create a user account.
Args:
email: Unique email address for the account.
name: Display name for the user.
Returns:
The created user.
"""
return user_repository.create(email=email, name=name)
验证模式
from pydantic import BaseModel, EmailStr, Field
class CreateUserRequest(BaseModel):
email: EmailStr
age: int = Field(ge=0, le=150)
OOP 模式
# Dataclass
@dataclass
class User:
name: str
email: str
# Protocol for interfaces
class Repository(Protocol):
def get(self, id: str) -> Entity: ...
# Property
@property
def full_name(self) -> str:
return f"{self.first} {self.last}"
另请参阅
- 推荐工具 - 用于自动强制执行这些规范的工具(ruff、mypy、pytest、pyscn、uv)
评论
支持 Markdown