mcpField
C
coding-standards

coding-standards

github.com/ludo-technologies开发3446 次安装1 周前更新
代码仓库

关于 coding-standards

面向 AI Agent 和大模型的 Python 编码规范集合,按性能、异步处理、设计、文档、验证和面向对象编程组织建议,并提供常见模式示例。

主要功能

  1. 01错误处理规则
  2. 02性能优化模式
  3. 03异步处理指南
  4. 04设计与 SOLID 原则
  5. 05文档和类型提示规范

适用场景

  1. 01指导 Python 代码生成
  2. 02检查 Python 实现模式
  3. 03采用异步资源管理实践
  4. 04统一公共 API 文档规范

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/ludo-technologies/python-best-practices --skill coding-standards

安装后在 Claude Code 中输入/coding-standards确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

metadata.json
README.md
rules/
_sections.md
_template.md
async-context-manager.md
async-create-task.md
async-gather.md
async-semaphore.md
design-dependency-injection.md
design-early-return.md
design-no-global-singleton.md
design-philosophy.md
design-pure-functions.md
design-single-responsibility.md
doc-docstring.md
doc-type-hints.md
error-no-silent-exceptions.md
oop-composition-over-inheritance.md
oop-dataclass.md
oop-property.md
oop-protocol.md
perf-dict-get.md
perf-generator-expression.md
perf-list-comprehension.md
perf-set-lookup.md
perf-str-join.md
solid-isp.md
solid-lsp.md
solid-ocp.md
validation-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-philosophyDRY、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