claude-code/claude-zh/rules/python/patterns.md

40 lines
956 B
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
paths:
- "**/*.py"
- "**/*.pyi"
---
# Python 模式 (Patterns)
> 本檔案擴展了 [common/patterns.md](../common/patterns.md),包含 Python 特定內容。
## 協定 (Protocol / 鴨子型別)
```python
from typing import Protocol
class Repository(Protocol):
def find_by_id(self, id: str) -> dict | None: ...
def save(self, entity: dict) -> dict: ...
```
## 使用 Dataclasses 作為 DTO (資料傳輸物件)
```python
from dataclasses import dataclass
@dataclass
class CreateUserRequest:
name: str
email: str
age: int | None = None
```
## 上下文管理器 (Context Managers) 與 生成器 (Generators)
- 使用上下文管理器 (`with` 語句) 進行資源管理。
- 使用生成器進行延遲求值與具備記憶體效率的迭代。
## 參考資源
參見技能 (Skill)`python-patterns`,獲取包含裝飾器 (Decorators)、併發 (Concurrency) 與包組織 (Package organization) 的全面模式。