python-code-style by wshobson/agents
npx skills add https://github.com/wshobson/agents --skill python-code-style一致的代码风格和清晰的文档规范能够提升代码库的可维护性和协作效率。本技能涵盖现代 Python 工具链、命名约定和文档标准。
让工具来处理格式化的争论。一次性配置,自动强制执行。
遵循 PEP 8 规范,使用有意义、描述性的名称。
文档字符串应与其描述的代码一同维护。
现代 Python 代码应为所有公共 API 包含类型提示。
# 安装现代工具链
pip install ruff mypy
# 在 pyproject.toml 中配置
[tool.ruff]
line-length = 120
target-version = "py312" # 根据项目的最低 Python 版本进行调整
[tool.mypy]
strict = true
使用 ruff 作为一体化的代码检查器和格式化工具。它用一个快速工具替代了 flake8、isort 和 black。
# pyproject.toml
[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"
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
运行命令:
ruff check --fix . # 检查并自动修复
ruff format . # 格式化代码
为生产代码配置严格的类型检查。
# 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"
遵循 PEP 8,强调清晰性而非简洁性。
文件和模块:
# 良好:描述性的 snake_case
user_repository.py
order_processing.py
http_client.py
# 避免:缩写
usr_repo.py
ord_proc.py
http_cli.py
类和函数:
# 类:PascalCase
class UserRepository:
pass
class HTTPClientFactory: # 首字母缩略词保持大写
pass
# 函数和变量:snake_case
def get_user_by_email(email: str) -> User | None:
retry_count = 3
max_connections = 100
常量:
# 模块级常量:SCREAMING_SNAKE_CASE
MAX_RETRY_ATTEMPTS = 3
DEFAULT_TIMEOUT_SECONDS = 30
API_BASE_URL = "https://api.example.com"
按照一致的顺序分组导入:标准库、第三方库、本地模块。
# 标准库
import os
from collections.abc import Callable
from typing import Any
# 第三方包
import httpx
from pydantic import BaseModel
from sqlalchemy import Column
# 本地导入
from myproject.models import User
from myproject.services import UserService
仅使用绝对导入:
# 推荐
from myproject.utils import retry_decorator
# 避免相对导入
from ..utils import retry_decorator
为所有公共类、方法和函数编写文档字符串。
简单函数:
def get_user(user_id: str) -> User:
"""根据唯一标识符检索用户。"""
...
复杂函数:
def process_batch(
items: list[Item],
max_workers: int = 4,
on_progress: Callable[[int, int], None] | None = None,
) -> BatchResult:
"""使用工作池并发处理项目。
使用配置的工作线程数处理批次中的每个项目。
可以通过可选的回调函数监控进度。
Args:
items: 要处理的项目。不能为空。
max_workers: 最大并发工作线程数。默认为 4。
on_progress: 接收 (已完成数, 总数) 计数的可选回调函数。
Returns:
包含成功项目和任何失败项及其关联异常的 BatchResult。
Raises:
ValueError: 如果 items 为空。
ProcessingError: 如果批次无法处理。
Example:
>>> result = process_batch(items, max_workers=8)
>>> print(f"Processed {len(result.succeeded)} items")
"""
...
类文档字符串:
class UserService:
"""管理用户操作的服务。
提供创建、检索、更新和删除用户的方法,
并包含适当的验证和错误处理。
Attributes:
repository: 用户持久化的数据访问层。
logger: 用于操作跟踪的日志记录器实例。
Example:
>>> service = UserService(repository, logger)
>>> user = service.create_user(CreateUserInput(...))
"""
def __init__(self, repository: UserRepository, logger: Logger) -> None:
"""初始化用户服务。
Args:
repository: 用户的数据访问层。
logger: 用于跟踪操作的日志记录器。
"""
self.repository = repository
self.logger = logger
为适应现代显示器,将行长度设置为 120 个字符,同时保持可读性。
# 良好:可读的换行
def create_user(
email: str,
name: str,
role: UserRole = UserRole.MEMBER,
notify: bool = True,
) -> User:
...
# 良好:清晰地链式调用方法
result = (
db.query(User)
.filter(User.active == True)
.order_by(User.created_at.desc())
.limit(10)
.all()
)
# 良好:格式化长字符串
error_message = (
f"Failed to process user {user_id}: "
f"received status {response.status_code} "
f"with body {response.text[:100]}"
)
README 结构:
# 项目名称
项目功能的简要描述。
## 安装
```bash
pip install myproject
from myproject import Client
client = Client(api_key="...")
result = client.process(data)
记录环境变量和配置选项。
pip install -e ".[dev]"
pytest
**CHANGELOG 格式(遵循 Keep a Changelog):**
```markdown
# 更新日志
## [未发布]
### 新增
- 新功能 X
### 变更
- 修改了 Y 的行为
### 修复
- Z 中的错误
每周安装量
4.0K
代码仓库
GitHub 星标数
32.2K
首次出现
2026年1月30日
安全审计
安装于
opencode3.3K
gemini-cli3.2K
codex3.2K
github-copilot3.0K
cursor2.8K
kimi-cli2.7K
Consistent code style and clear documentation make codebases maintainable and collaborative. This skill covers modern Python tooling, naming conventions, and documentation standards.
Let tools handle formatting debates. Configure once, enforce automatically.
Follow PEP 8 conventions with meaningful, descriptive names.
Docstrings should be maintained alongside the code they describe.
Modern Python code should include type hints for all public APIs.
# 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
Use ruff as an all-in-one linter and formatter. It replaces flake8, isort, and black with a single fast tool.
# 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:
ruff check --fix . # Lint and auto-fix
ruff format . # Format code
Configure strict type checking for production code.
# 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.
[tool.pyright]
pythonVersion = "3.12"
typeCheckingMode = "strict"
Follow PEP 8 with emphasis on clarity over brevity.
Files and Modules:
# 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 and Functions:
# 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
Constants:
# Module-level constants: SCREAMING_SNAKE_CASE
MAX_RETRY_ATTEMPTS = 3
DEFAULT_TIMEOUT_SECONDS = 30
API_BASE_URL = "https://api.example.com"
Group imports in a consistent order: standard library, third-party, local.
# 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
Use absolute imports exclusively:
# Preferred
from myproject.utils import retry_decorator
# Avoid relative imports
from ..utils import retry_decorator
Write docstrings for all public classes, methods, and functions.
Simple Function:
def get_user(user_id: str) -> User:
"""Retrieve a user by their unique identifier."""
...
Complex Function:
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:
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
Set line length to 120 characters for modern displays while maintaining readability.
# 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]}"
)
README Structure:
# 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 Format (Keep a Changelog):
# Changelog
## [Unreleased]
### Added
- New feature X
### Changed
- Modified behavior of Y
### Fixed
- Bug in Z
Weekly Installs
4.0K
Repository
GitHub Stars
32.2K
First Seen
Jan 30, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode3.3K
gemini-cli3.2K
codex3.2K
github-copilot3.0K
cursor2.8K
kimi-cli2.7K
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装
AI代码审查工具 - 自动化安全漏洞检测与代码质量分析 | 支持多领域检查清单
1,200 周安装
AI智能体长期记忆系统 - 精英级架构,融合6种方法,永不丢失上下文
1,200 周安装
AI新闻播客制作技能:实时新闻转对话式播客脚本与音频生成
1,200 周安装
Word文档处理器:DOCX创建、编辑、分析与修订痕迹处理全指南 | 自动化办公解决方案
1,200 周安装
React Router 框架模式指南:全栈开发、文件路由、数据加载与渲染策略
1,200 周安装
Nano Banana AI 图像生成工具:使用 Gemini 3 Pro 生成与编辑高分辨率图像
1,200 周安装