
Python Dev
Python 开发规范,包含 PEP 8 风格、类型注解、异常处理、测试规范等
Install
npx skills add doccker/cc-use-exp --skill python-dev -g -a claude-code -y- Repository
- doccker/cc-use-exp1.1k
- Category
- Engineering
- Updated
- 2mo ago
- License
- See repository
- Context cost
- Lightabout 1,288 tokens
- Runs scripts
- No, instructions only
What it does
Python 开发规范,包含 PEP 8 风格、类型注解、异常处理、测试规范等
Python 开发规范
参考来源: PEP 8、Google Python Style Guide
工具链
# 格式化
black . # 代码格式化
isort . # import 排序
# 类型检查
mypy . # 静态类型检查
pyright . # 备选
# 代码检查
ruff check . # 快速 linter(推荐)
flake8 . # 传统 linter
# 测试
pytest -v # 运行测试
pytest --cov=src # 覆盖率
命名约定
| 类型 | 规则 | 示例 |
|---|---|---|
| 模块/包 | 小写下划线 | user_service.py |
| 类名 | 大驼峰 | UserService, HttpClient |
| 函数/变量 | 小写下划线 | get_user_by_id, user_name |
| 常量 | 全大写下划线 | MAX_RETRY_COUNT |
| 私有 | 单下划线前缀 | _internal_method |
类型注解
from typing import Optional, List, Dict, Union
from dataclasses import dataclass
@dataclass
class User:
id: int
name: str
email: Optional[str] = None
def find_user_by_id(user_id: int) -> Optional[User]:
"""根据 ID 查找用户"""
...
def process_items(items: List[str]) -> Dict[str, int]:
"""处理项目列表"""
return {item: len(item) for item in items}
# Python 3.10+ 可用新语法
def greet(name: str | None = None) -> str:
return f"Hello, {name or 'World'}"
异常处理
# ✅ 好:捕获具体异常
try:
user = repository.find_by_id(user_id)
except DatabaseError as e:
logger.error(f"Failed to find user {user_id}: {e}")
raise ServiceError(f"Database error: {e}") from e
# ✅ 好:上下文管理器
with open("file.txt", "r") as f:
content = f.read()
# ❌ 差:裸 except
try:
do_something()
except: # 永远不要这样做
pass
自定义异常
class ServiceError(Exception):
"""服务层异常基类"""
def __init__(self, message: str, code: str = "UNKNOWN"):
super().__init__(message)
self.code = code
class UserNotFoundError(ServiceError):
"""用户不存在"""
def __init__(self, user_id: int):
super().__init__(f"User {user_id} not found", "USER_NOT_FOUND")
self.user_id = user_id
