designing-python-apis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python API Design

Python API 设计

Core Principles

核心原则

  1. Simplicity: Simple things simple, complex things possible
  2. Consistency: Similar operations work similarly
  3. Least Surprise: Behave as users expect
  4. Discoverability: Find via autocomplete and help
  1. 简洁性:简单的事简单实现,复杂的事具备可行性
  2. 一致性:相似操作采用相同实现逻辑
  3. 最小意外:行为符合用户预期
  4. 易发现性:可通过自动补全和帮助功能找到相关内容

Progressive Disclosure Pattern

渐进式暴露模式

python
undefined
python
undefined

Level 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
undefined
from mylib.internals import BitEncoder
undefined

Naming Conventions

命名规范

python
undefined
python
undefined

Actions: 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()
undefined
to_dict(), from_json()
undefined

Error Handling

错误处理

python
class MyLibError(Exception):
    """Base exception with helpful messages."""
    def __init__(self, message: str, *, hint: str = None):
        super().__init__(message)
        self.hint = hint
python
class MyLibError(Exception):
    """Base exception with helpful messages."""
    def __init__(self, message: str, *, hint: str = None):
        super().__init__(message)
        self.hint = hint

Usage

Usage

raise ValidationError( f"Latitude must be -90 to 90, got {lat}", hint="Did you swap latitude and longitude?" )
undefined
raise ValidationError( f"Latitude must be -90 to 90, got {lat}", hint="Did you swap latitude and longitude?" )
undefined

Deprecation

弃用处理

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
undefined
python
undefined

Bad: 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 guides
def 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)章节。