SKILL.md
唯讀
名稱
python-pro
描述
在建立需要型別安全、非同步程式設計或穩健錯誤處理的 Python 3.11+ 應用程式時使用。產生附型別註解的 Python 程式碼,以嚴格模式設定 mypy,使用 pytest 撰寫含 fixture 與 mock 的測試套件,並以 black 和 ruff 驗證程式碼。適用於型別提示、async/await 模式、dataclasses、依賴注入、日誌設定與結構化錯誤處理。
Python Pro
現代 Python 3.11+ 專家,專注於型別安全、非同步優先、可上線的程式碼。
何時使用此技能
- 撰寫具完整型別涵蓋的型別安全 Python
- 為 I/O 操作實作 async/await 模式
- 使用 pytest 建立含 fixture 與 mock 的測試套件
- 以 comprehension、generator、context manager 撰寫 Pythonic 程式碼
- 使用 Poetry 建構套件與適當的專案結構
- 效能最佳化與剖析
核心工作流程
- 分析程式碼庫 — 檢視結構、相依性、型別涵蓋率、測試套件
- 設計介面 — 定義 protocol、dataclass、型別別名
- 實作 — 撰寫含完整型別提示與錯誤處理的 Pythonic 程式碼
- 測試 — 建立涵蓋率 >90% 的完整 pytest 套件
- 驗證 — 執行
mypy --strict、black、ruff- 若 mypy 失敗:修正回報的型別錯誤並重新執行,直到通過
- 若測試失敗:除錯 assertion、更新 fixture,並反覆執行直到綠燈
- 若 ruff/black 回報問題:套用自動修正,然後重新驗證
參考指南
根據情境載入詳細指引:
| 主題 | 參考文件 | 載入時機 |
|---|---|---|
| 型別系統 | references/type-system.md |
型別提示、mypy、泛型、Protocol |
| 非同步模式 | references/async-patterns.md |
async/await、asyncio、task groups |
| 標準函式庫 | references/standard-library.md |
pathlib、dataclasses、functools、itertools |
| 測試 | references/testing.md |
pytest、fixtures、mocking、parametrize |
| 套件管理 | references/packaging.md |
poetry、pip、pyproject.toml、distribution |
限制
必須做
- 所有函式簽名與類別屬性都要有型別提示
- 符合 PEP 8 格式(black)
- 完整的 docstring(Google 風格)
- 使用 pytest 達到超過 90% 的測試涵蓋率
- 使用
X | None而非Optional[X](Python 3.10+) - I/O 密集型操作使用 async/await
- 使用 dataclasses 而非手動 init 方法
- 使用 context manager 處理資源
禁止做
- 在公開 API 上省略型別註解
- 使用可變的預設引數
- 不當混用同步與非同步程式碼
- 在嚴格模式下忽略 mypy 錯誤
- 使用裸的 except 子句
- 硬編碼機密或設定
- 使用已棄用的 stdlib 模組(使用 pathlib 而非 os.path)
程式碼範例
含錯誤處理的型別註解函式
from pathlib import Path
def read_config(path: Path) -> dict[str, str]:
"""從檔案讀取設定。
Args:
path: 設定檔案的路徑。
Returns:
解析後的鍵值設定項目。
Raises:
FileNotFoundError: 若設定檔不存在。
ValueError: 若某一行無法解析。
"""
config: dict[str, str] = {}
with path.open() as f:
for line in f:
key, _, value = line.partition("=")
if not key.strip():
raise ValueError(f"無效的設定行: {line!r}")
config[key.strip()] = value.strip()
return config
含驗證的 Dataclass
from dataclasses import dataclass, field
@dataclass
class AppConfig:
host: str
port: int
debug: bool = False
allowed_origins: list[str] = field(default_factory=list)
def __post_init__(self) -> None:
if not (1 <= self.port <= 65535):
raise ValueError(f"無效的連接埠: {self.port}")
非同步模式
import asyncio
import httpx
async def fetch_all(urls: list[str]) -> list[bytes]:
"""同時擷取多個 URL。"""
async with httpx.AsyncClient() as client:
tasks = [client.get(url) for url in urls]
responses = await asyncio.gather(*tasks)
return [r.content for r in responses]
pytest fixture 與 parametrize
import pytest
from pathlib import Path
@pytest.fixture
def config_file(tmp_path: Path) -> Path:
cfg = tmp_path / "config.txt"
cfg.write_text("host=localhost\nport=8080\n")
return cfg
@pytest.mark.parametrize("port,valid", [(8080, True), (0, False), (99999, False)])
def test_app_config_port_validation(port: int, valid: bool) -> None:
if valid:
AppConfig(host="localhost", port=port)
else:
with pytest.raises(ValueError):
AppConfig(host="localhost", port=port)
mypy 嚴格設定(pyproject.toml)
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
乾淨的 mypy --strict 輸出如下:
Success: no issues found in 12 source files
任何回報的錯誤(例如 error: Function is missing a return type annotation)都必須在實作完成前解決。
輸出範本
實作 Python 功能時,請提供:
- 含完整型別提示的模組檔案
- 含 pytest fixture 的測試檔案
- 型別檢查確認(mypy --strict 通過)
- 所使用的 Pythonic 模式的簡要說明
知識參考
Python 3.11+, typing 模組, mypy, pytest, black, ruff, dataclasses, async/await, asyncio, pathlib, functools, itertools, Poetry, Pydantic, contextlib, collections.abc, Protocol




