Skills

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
Read the whole SKILL.md on GitHub

More in Engineering