designing-python-apis
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython API Design
Python API 设计
Core Principles
核心原则
- Simplicity: Simple things simple, complex things possible
- Consistency: Similar operations work similarly
- Least Surprise: Behave as users expect
- Discoverability: Find via autocomplete and help
- 简洁性:简单的事简单实现,复杂的事具备可行性
- 一致性:相似操作采用相同实现逻辑
- 最小意外:行为符合用户预期
- 易发现性:可通过自动补全和帮助功能找到相关内容
Progressive Disclosure Pattern
渐进式暴露模式
python
undefinedpython
undefinedLevel 1: Simple functions
Level 1: Simple functions
from mylib import encode, decode
result = encode(37.7749, -122.4194)
from mylib import encode, decode
result = encode(37.7749, -122.4194)
Level 2: Configurable classes
Level 2: Configurable classes
from mylib import Encoder
encoder = Encoder(precision=15)
from mylib import Encoder
encoder = Encoder(precision=15)
Level 3: Low-level access
Level 3: Low-level access
from mylib.internals import BitEncoder
undefinedfrom mylib.internals import BitEncoder
undefinedNaming Conventions
命名规范
python
undefinedpython
undefinedActions: verbs
Actions: verbs
encode(), decode(), validate()
encode(), decode(), validate()
Retrieval: get_*
Retrieval: get_*
get_user(), get_config()
get_user(), get_config()
Boolean: is_, has_, can_*
Boolean: is_, has_, can_*
is_valid(), has_permission()
is_valid(), has_permission()
Conversion: to_, from_
Conversion: to_, from_
to_dict(), from_json()
undefinedto_dict(), from_json()
undefinedError Handling
错误处理
python
class MyLibError(Exception):
"""Base exception with helpful messages."""
def __init__(self, message: str, *, hint: str = None):
super().__init__(message)
self.hint = hintpython
class MyLibError(Exception):
"""Base exception with helpful messages."""
def __init__(self, message: str, *, hint: str = None):
super().__init__(message)
self.hint = hintUsage
Usage
raise ValidationError(
f"Latitude must be -90 to 90, got {lat}",
hint="Did you swap latitude and longitude?"
)
undefinedraise ValidationError(
f"Latitude must be -90 to 90, got {lat}",
hint="Did you swap latitude and longitude?"
)
undefinedDeprecation
弃用处理
python
import warnings
def old_function():
warnings.warn(
"old_function() deprecated, use new_function()",
DeprecationWarning,
stacklevel=2,
)
return new_function()python
import warnings
def old_function():
warnings.warn(
"old_function() deprecated, use new_function()",
DeprecationWarning,
stacklevel=2,
)
return new_function()Anti-Patterns
反模式
python
undefinedpython
undefinedBad: Boolean trap
Bad: Boolean trap
process(data, True, False, True)
process(data, True, False, True)
Good: Keyword arguments
Good: Keyword arguments
process(data, validate=True, cache=False)
process(data, validate=True, cache=False)
Bad: Mutable default
Bad: Mutable default
def process(items: list = []):
def process(items: list = []):
Good: None default
Good: None default
def process(items: list | None = None):
For detailed patterns, see:
- **[PATTERNS.md](PATTERNS.md)** - Builder, factory, and advanced patterns
- **[EVOLUTION.md](EVOLUTION.md)** - API versioning and migration guidesdef process(items: list | None = None):
如需了解详细模式,请查看:
- **[PATTERNS.md](PATTERNS.md)** - 构建器、工厂及高级模式
- **[EVOLUTION.md](EVOLUTION.md)** - API版本管理与迁移指南Review Checklist
审查清单
Naming:
- [ ] Clear, self-documenting names
- [ ] Consistent patterns throughout
- [ ] Boolean params read naturally
Parameters:
- [ ] Minimal required parameters
- [ ] Sensible defaults
- [ ] Keyword-only after positional clarity
Errors:
- [ ] Custom exceptions with context
- [ ] Helpful error messages
- [ ] Documented in docstrings命名:
- [ ] 清晰、自文档化的命名
- [ ] 全程遵循一致的命名模式
- [ ] 布尔型参数表述自然
参数:
- [ ] 仅保留必要的最少参数
- [ ] 合理的默认值
- [ ] 位置参数明确后使用关键字-only参数
错误:
- [ ] 带上下文的自定义异常
- [ ] 有帮助性的错误信息
- [ ] 在文档字符串中记录异常信息Learn More
了解更多
This skill is based on the Ergonomics section of the Guide to Developing High-Quality Python Libraries by Will McGinnis.
本技能基于Will McGinnis所著《高质量Python库开发指南》(Guide to Developing High-Quality Python Libraries)中的「人机工程学」(Ergonomics)章节。