Pythonic idioms, PEP 8 standards, type hints, and best practices for building robust, efficient, and maintainable Python applications.
View on GitHubxu-xiang/everything-claude-code-zh
everything-claude-code
February 5, 2026
Select agents to install to:
npx add-skill https://github.com/xu-xiang/everything-claude-code-zh/blob/main/skills/python-patterns/SKILL.md -a claude-code --skill python-patternsInstallation paths:
.claude/skills/python-patterns/# Python 开发模式 (Python Development Patterns)
构建健壮、高效且可维护的应用程序的 Pythonic 惯用模式和最佳实践。
## 激活时机 (When to Activate)
- 编写新的 Python 代码时
- 进行 Python 代码审查(Review)时
- 重构现有的 Python 代码时
- 设计 Python 包(Package)或模块(Module)时
## 核心原则
### 1. 可读性至上 (Readability Counts)
Python 优先考虑可读性。代码应当直观且易于理解。
```python
# Good: 清晰且易读
def get_active_users(users: list[User]) -> list[User]:
"""仅从提供的列表中返回活跃用户。"""
return [user for user in users if user.is_active]
# Bad: 巧妙但令人困惑
def get_active_users(u):
return [x for x in u if x.a]
```
### 2. 显式优于隐式 (Explicit is Better Than Implicit)
避免“魔法”行为;清晰地表达代码的功能。
```python
# Good: 显式配置
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Bad: 隐藏的副作用
import some_module
some_module.setup() # 这到底做了什么?
```
### 3. EAFP 模式 - 请求宽恕比请求许可更容易 (Easier to Ask Forgiveness Than Permission)
Python 倾向于使用异常处理而非预先检查条件。
```python
# Good: EAFP 风格
def get_value(dictionary: dict, key: str) -> Any:
try:
return dictionary[key]
except KeyError:
return default_value
# Bad: 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)
### 基础类型注解
```python
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
# 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}
```
### 类型别名 (Type Aliases) 和 TypeVar
```python
from typing import TypeVar, Unio