Skip to content
Development
Skill

/python-patterns

构建健壮、高效且易于维护的 Python 应用程序的 Python 惯用法(Pythonic idioms)、PEP 8 标准、类型提示(Type hints)以及最佳实践。

From plugin
everything-claude-code
1.8k59 skills15 agents35 commands6 hooks
Install
$ npx -y skills add xu-xiang/everything-claude-code-zh --skill python-patterns --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
  • You can call itInvoke it directly when you want it.
  • Slash command/python-patterns

Context preview

The summary Claude sees to decide when to auto-load this skill.

构建健壮、高效且易于维护的 Python 应用程序的 Python 惯用法(Pythonic idioms)、PEP 8 标准、类型提示(Type hints)以及最佳实践。

SKILL.md

python-patterns.SKILL.md
name: python-patterns
description: 构建健壮、高效且易于维护的 Python 应用程序的 Python 惯用法(Pythonic idioms)、PEP 8 标准、类型提示(Type hints)以及最佳实践。
origin: ECC

Python 开发模式 (Python Development Patterns)

用于构建健壮、高效且易于维护的应用程序的 Python 惯用模式与最佳实践。

何时激活

  • 编写新的 Python 代码时
  • 评审 Python 代码时
  • 重构现有的 Python 代码时
  • 设计 Python 包(Packages)或模块(Modules)时

核心原则

1. 可读性至上 (Readability Counts)

Python 优先考虑可读性。代码应当直观且易于理解。

# 推荐:清晰且可读
def get_active_users(users: list[User]) -> list[User]:
    """仅从提供的列表中返回活跃用户。"""
    return [user for user in users if user.is_active]


# 不推荐:虽然精简但令人困惑
def get_active_users(u):
    return [x for x in u if x.a]

2. 显式优于隐式 (Explicit is Better Than Implicit)

避免使用“魔法”;确保代码的行为清晰透明。

# 推荐:显式配置
import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# 不推荐:隐藏的副作用
import some_module
some_module.setup()  # 这行代码具体做了什么?

3. EAFP - 宽恕好过许可 (Easier to Ask Forgiveness Than Permission)

Python 倾向于使用异常处理而非预先检查条件。

# 推荐:EAFP 风格
def get_value(dictionary: dict, key: str) -> Any:
    try:
        return dictionary[key]
    except KeyError:
        return default_value

# 不推荐:LBYL (Look Before You Leap) 风格
def get_value(dictionary: dict, key: str) -> Any:
    if key in dictionary:
        return dictionary[key]
    else:
        return default_value

类型提示 (Type Hints)

基础类型标注

from typing import Optional, List, Dict, Any

def process_user(
    user_id: str,
    data: Dict[str, Any],
    active: bool = True
) -> Optional[User]:
    """处理用户并返回更新后的 User 对象或 None。"""
    if not active:
        return None
    return User(user_id, data)

现代类型提示 (Python 3.9+)

# Python 3.9+ - 使用内置类型
def process_items(items: list[str]) -> dict[str, int]:
    return {item: len(item) for item in items}

# Python 3.8 及更早版本 - 使用 typing 模块
from typing import List, Dict

def process_items(items: List[str]) -> Dict[str, int]:
    return {item: len(item) for item in items}

类型别名与 TypeVar

from typing import TypeVar, Union

# 复杂类型的类型别名
JSON = Union[dict[str, Any], list[Any], str, int, float, bool, None]

def parse_json(data: str) -> JSON:
    return json.loads(data)

# 泛型类型
T = TypeVar('T')

def first(items: list[T]) -> T | None:
    """返回第一项,如果列表为空则返回 None。"""
    return items[0] if items else None

基于协议 (Protocol) 的鸭子类型

from typing import Protocol

class Renderable(Protocol):
    def render(self) -> str:
        """将对象渲染为字符串。"""

def render_all(items: list[Renderable]) -> str:
    """渲染所有实现了 Renderable 协议的项。"""
    return "\n".join(item.render() for item in items)

错误处理模式

特定的异常处理

# 推荐:捕获特定的异常
def load_config(path: str) -> Config:
    try:
        with open(path) as f:
            return Config.from_json(f.read())
    except FileNotFoundError as e:
        raise ConfigError(f"未找到配置文件: {path}") from e
    except json.JSONDecodeError as e:
        raise ConfigError(f"配置文件中的 JSON 无效: {path}") from e

# 不推荐:空 except
def load_config(path: str) -> Config:
    try:
        with open(path) as f:
            return Config.from_json(f.read())
    except:
        return None  # 静默失败!

异常链 (Exception Chaining)

def process_data(data: str) -> Result:
    try:
        parsed = json.loads(data)
    except json.JSONDecodeError as e:
        # 链接异常以保留回溯信息
        raise ValueError(f"无法解析数据: {data}") from e

自定义异常层级

class AppError(Exception):
    """所有应用程序错误的基类。"""
    pass

class ValidationError(AppError):
    """当输入验证失败时抛出。"""
    pass

class NotFoundError(AppError):
    """当请求的资源未找到时抛出。"""
    pass

# 用法
def get_user(user_id: str) -> User:
    user = db.find_user(user_id)
    if not user:
        raise NotFoundError(f"未找到用户: {user_id}")
    return user

上下文管理器 (Context Managers)

资源管理

# 推荐:使用上下文管理器
def process_file(path: str) -> str:
    with open(path, 'r') as f:
        return f.read()

# 不推荐:手动资源管理
def process_file(path: str) -> str:
    f = open(path, 'r')
    try:
        return f.read()
    finally:
        f.close()

自定义上下文管理器

from contextlib import contextmanager

@contextmanager
def timer(name: str):
    """计时代码块的上下文管理器。"""
    start = time.perf_counter()
    yield
    elapsed = time.perf_counter() - start
    print(f"{name} 耗时 {elapsed:.4f} 秒")

# 用法
with timer("数据处理"):
    process_large_dataset()

上下文管理器类

class DatabaseTransaction:
    def __init__(self, connection):
        self.connection = connection

    def __enter__(self):
        self.connection.begin_transaction()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is None:
            self.connection.commit()
        else:
            self.connection.rollback()
        return False  # 不要抑制异常

# 用法
with DatabaseTransaction(conn):
    user = conn.create_user(user_data)
    conn.create_profile(user.id, profile_data)

推导式 (Comprehensions) 与生成器 (Generators)

列表推导式 (List Comprehensions)

# 推荐:使用列表推导式进行简单的转换
names = [user.name for user in users if user.is_active]

# 不推荐:手动循环
names = []
for user in users:
    if user.is_active:
        names.append(user.name)

# 复杂的推导式应当展开
# 不推荐:过于复杂
result = [x * 2 for x in items if x > 0 if x % 2 == 0]

# 推荐:使用生成器函数
def filter_and_transform(items: Iterable[int]) -> list[int]:
    result = []
    for x in items:
        if x > 0 and x % 2 == 0:
            result.append(x * 2)
    return result

生成器表达式 (Generator Expressions)

# 推荐:使用生成器进行惰性求值
total = sum(x * x for x in range(1_000_000))

# 不推荐:创建大型中间列表
total = sum([x * x for x in range(1_000_000)])

生成器函数

def read_large_file(path: str) -> Iterator[str]:
    """逐行读取大文件。"""
    with open(path) as f:
        for line in f:
            yield line.strip()

# 用法
for line in read_large_file("huge.txt"):
    process(line)

数据类 (Data Classes) 与具名元组 (Named Tuples)

数据类 (Data Classes)

f
Read more
Ships witheverything-claude-code

🌐 Language / 语言 / 語言 为 AI 智能体(Agent)框架打造的性能优化系统。源自 Anthropic 黑客松获胜作品。 这不仅仅是配置文件。它是一个完整的系统:包含技能(Skills)、本能(Instincts)、内存优化、持续学习、安全扫描以及研究优先的开发模式。这些生产级的智能体(Agents)、钩子(Hooks)、命令(Commands)、规则(Rules)以及 MCP 配置,是在构建真实产品的 10 个多月高强度日常使用中演化而来的。 适用于 Claude Code, Codex,

Get the whole plugin