关于 python-code-style
python-code-style 面向编写、审查或规范 Python 代码的开发者,提供风格指导。内容涵盖命名、格式、检查、类型检查、导入和文档,并包含 ruff、mypy 与 pyright 等工具示例。
主要功能
- 01ruff 格式化与代码检查
- 02mypy 和 pyright 配置
- 03PEP 8 命名约定
- 04导入组织实践
- 05Google 风格文档字符串指导
- 06公共 API 类型注解建议
适用场景
- 01配置 Python 代码检查与格式化
- 02审查代码风格一致性
- 03制定团队 Python 编码规范
- 04编写或审查 API 文档
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ full-stack-skills/ python-skills --skill python-code-style安装后在 Claude Code 中输入/python-code-style确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
LICENSE.txtagents/openai.yamlexamples/advanced-usage.mdbasic-usage.mdintegration.md详细介绍
来源声明:本技能内容源自 wshobson/agents (MIT License, Copyright (c) 2024 Seth Hobson;完整许可文本见同目录
LICENSE.txt)。 使用、修改与再分发须遵守该 MIT 许可条款并保留版权声明。
中文描述
本技能提供全栈开发相关的最佳实践和模式指导。
name: python-code-style description: Python 代码风格、lint、格式化、命名规范和文档标准。适用于编写新代码、审查风格、配置 lint 工具、编写文档字符串或制定项目标准。
Python 代码风格与文档
一致的代码风格和清晰的文档有助于代码库的维护与协作。本技能涵盖现代 Python 工具、命名规范和文档标准。
适用场景
- 为新项目配置 lint 和格式化
- 编写或审查文档字符串
- 制定团队编码标准
- 配置 ruff、mypy 或 pyright
- 审查代码风格的一致性
- 编写项目文档
核心概念
1. 自动格式化
将格式争论交给工具处理。一次配置,自动执行。
2. 统一命名
遵循 PEP 8 规范,使用有意义且具描述性的名称。
3. 将文档视为代码
应与代码一同维护对应的文档字符串。
4. 类型注解
现代 Python 代码应为所有公共 API 添加类型提示。
快速入门
# Install modern tooling
pip install ruff mypy
# Configure in pyproject.toml
[tool.ruff]
line-length = 120
target-version = "py312" # Adjust based on your project's minimum Python version
[tool.mypy]
strict = true
基本模式
模式 1:现代 Python 工具
使用 ruff 作为一体化 lint 和格式化工具。它用一个快速工具取代 flake8、isort 和 black。
# 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"
运行方式:
ruff check --fix . # Lint and auto-fix
ruff format . # Format code
模式 2:类型检查配置
为生产代码配置严格的类型检查。
# 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
或者,使用 pyright 进行更快的检查。
[tool.pyright]
pythonVersion = "3.12"
typeCheckingMode = "strict"
模式 3:命名规范
遵循 PEP 8,着重清晰而非简短。
文件和模块:
# Good: Descriptive snake_case
user_repository.py
order_processing.py
http_client.py
# Avoid: Abbreviations
usr_repo.py
ord_proc.py
http_cli.py
类和函数:
# Classes: PascalCase
class UserRepository:
pass
class HTTPClientFactory: # Acronyms stay uppercase
pass
# Functions and variables: snake_case
def get_user_by_email(email: str) -> User | None:
retry_count = 3
max_connections = 100
常量:
# Module-level constants: SCREAMING_SNAKE_CASE
MAX_RETRY_ATTEMPTS = 3
DEFAULT_TIMEOUT_SECONDS = 30
API_BASE_URL = "https://api.example.com"
模式 4:导入组织
按照一致的顺序对导入分组:标准库、第三方库、本地模块。
# Standard library
import os
from collections.abc import Callable
from typing import Any
# Third-party packages
import httpx
from pydantic import BaseModel
from sqlalchemy import Column
# Local imports
from myproject.models import User
from myproject.services import UserService
只使用绝对导入:
# Preferred
from myproject.utils import retry_decorator
# Avoid relative imports
from ..utils import retry_decorator
进阶模式
模式 5:Google 风格的文档字符串
为所有公共类、方法和函数编写文档字符串。
简单函数:
def get_user(user_id: str) -> User:
"""Retrieve a user by their unique identifier."""
...
复杂函数:
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 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
模式 6:行长度和格式化
将行长度设为 120 个字符,以适配现代显示屏,同时保持可读性。
# Good: Readable line breaks
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()
)
# 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]}"
)
模式 7:项目文档
README 结构:
# Project Name
Brief description of what the project does.
## Installation
\`\`\`bash
pip install myproject
\`\`\`
## Quick Start
\`\`\`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 格式(Keep a Changelog):
# Changelog
## [Unreleased]
### Added
- New feature X
### Changed
- Modified behavior of Y
### Fixed
- Bug in Z
最佳实践总结
- 使用 ruff - 用单一工具进行 lint 和格式化
- 启用严格的 mypy - 在运行前捕获类型错误
- 每行 120 个字符 - 现代可读性标准
- 使用描述性名称 - 清晰胜于简短
- 使用绝对导入 - 比相对导入更易维护
- 使用 Google 风格的文档字符串 - 文档一致且易读
- 为公共 API 编写文档 - 每个公共函数都需要文档字符串
- 及时更新文档 - 将文档视为代码
- 在 CI 中自动化 - 每次提交都运行 lint 工具
- 以 Python 3.10+ 为目标版本 - 新项目推荐使用 Python 3.12+,以采用现代语言特性
能力边界
✅ 擅长处理
- 全栈开发相关的最佳实践
- 代码架构设计指导
- 性能优化建议
⚠️ 需要素材
- 具体的项目上下文
- 技术栈信息
❌ 超出范围
- 非技术领域的业务决策
- 具体的代码实现(仅提供指导)
工作流程
步骤 1:需求分析
理解项目需求和技术约束
步骤 2:架构设计
设计系统架构和组件划分
步骤 3:实现指导
提供具体的实现建议和代码模式
步骤 4:代码审查
审查代码质量和最佳实践遵循情况
步骤 5:优化建议
提供性能优化和改进建议
注意事项
1. 过度设计
避免在简单场景中使用复杂的设计模式
2. 忽视性能
不要忽视性能优化,特别是在生产环境中
3. 安全考虑
始终考虑安全性和数据保护
4. 测试覆盖率
确保有足够的测试覆盖率,特别是边界情况
5. 文档维护
保持文档与代码同步更新