Python 程式設計 — 通用方法
這是 Python 的主要參考技能。它說明了此專案中所有 Python 程式碼中不可妥協的預設值與「函數式輕量」哲學。請先閱讀此文件,然後參閱連結的領域技能以獲得更深入的指導。
核心技術棧
| 關注點 | 選擇 |
|---|---|
| 套件管理器與任務執行器 | uv |
| 封裝清單 | 僅 pyproject.toml |
| Linter / Formatter | ruff |
| 型別檢查器 | ty |
| 資料處理函式庫 | polars (非 pandas) |
| 後端框架 | FastAPI |
| 資料庫 | PostgreSQL |
| ORM | SQLAlchemy (非同步) |
| 遷移工具 | Alembic |
| 執行模型 | asyncio — 始終非同步 |
| 程式設計風格 | 函數式輕量 |
套件管理 — 始終使用 uv
絕不直接使用 pip、pip-tools、poetry 或 pipenv。所有安裝、執行與腳本操作都需使用 uv 及其原生指令。
# 安裝依賴
uv sync
# 新增依賴
uv add <package>
# 新增開發依賴
uv add --dev <package>
# 執行腳本或模組
uv run python script.py
uv run alembic upgrade head
uv run pytest
# 升級依賴
uv lock --upgrade
所有生產環境的依賴必須使用 == 鎖定版本,以確保可重複建置。禁止使用 requirements.txt、requirements-dev.txt 或任何 requirements 目錄來管理依賴。所有套件元資料與依賴配置都必須放在 pyproject.toml 中。任何涉及套件、工具或建置的操作都必須使用 uv。請勿在本專案中直接執行 pip、pip install、python -m pip、poetry 或 pipenv。
請參閱upgrade-dependencies 技能以了解完整的升級工作流程:
.github/skills/upgrade-dependencies/SKILL.md
如需函式庫建立的具體指引,請參閱 .github/skills/python-library-creation/SKILL.md。
Linting 與格式化 — 強制使用 Astral 技術棧
本儲存庫的 Python 專案強制使用 Astral 技術棧。ruff 是權威的 linter 與 formatter。
- 將
ruff新增為開發依賴:uv add --dev ruff - 使用
uv run ruff format格式化程式碼。 - 使用
uv run ruff check --fix執行 lint 檢查並自動修正可能的問題。 - 將這些指令記錄在專案腳本或 README 中。
ruff 是程式碼、測試與配置在格式與風格一致性上的唯一真理來源。
型別檢查 — 優先使用 ty
型別註解是必需的。本儲存庫優先使用 ty 作為型別檢查器。
- 將
ty新增為開發依賴:uv add --dev ty - 使用
uv run ty check執行型別檢查 - 如果您想比較不同工具的行為,可使用
uv run --with ty ty check驗證工具鏈。
儲存庫可能仍會嘗試其他檢查器(如 mypy 或 pyrefly),但 ty 是首選的主要檢查器,應在 CI 中強制執行。
資料處理 — Polars vs DuckDB
本儲存庫偏好使用 polars 進行程序內資料工程,並使用 DuckDB 進行以 SQL 為優先的分析與大型檔案查詢。
-
當代理作為 Speedster 時使用 Polars:
- 基於 Rust、多執行緒的 DataFrame 處理,適用於單機環境。
- 最適合複雜的管道鏈、特徵工程、連接、窗口函數與程式化轉換。
- 優先考慮吞吐量與計算速度,提供更嚴格的 schema 與型別安全性。
- 非常適合模型預處理與整合 Python ML 工具。
-
當代理作為 Librarian 時使用 DuckDB:
- 程序內 SQL 資料庫,專為分析型 OLAP 查詢最佳化。
- 以 SQL 為先的意圖更可靠地將自然語言轉譯為程式碼。
- 更適合記憶體受限的工作負載:DuckDB 強制執行嚴格的記憶體限制,並能安全地查詢非常大的資料集。
- 適用於零 ETL 直接雲端查詢,透過 URL 查詢 S3 或 Google Cloud 上的遠端檔案。
決策啟發法
如果任務是:
- 探索新檔案或雲端儲存 → DuckDB
- 最擅長直接檔案掃描與 SQL 探索。
- 過濾或排序巨量資料集 → Polars
- 通常在原始過濾與單節點載入速度上佔優勢。
- 協作或交接 → DuckDB
- SQL 對人類與代理來說更易於維護與除錯。
- 模型預處理 → Polars
- 與 Python ML 工具及 schema 安全管道的整合性更佳。
後端 — FastAPI
FastAPI 是唯一支援的後端框架。主要慣例:
- 始終使用
async def定義路由處理器與依賴項。 - 使用 Pydantic v2 模型定義所有請求/回應結構。
- 使用
Depends()宣告依賴項——絕不在處理器內部存取全域狀態。 - 回傳型別化的回應模型;絕不從路由處理器回傳原始 dict。
- Router 位於各自的模組中;
main.py僅負責掛載路由器與配置中介軟體。
# ✅ 正確範例
@router.get("/items/{item_id}", response_model=ItemResponse)
async def get_item(item_id: int, db: AsyncSession = Depends(get_db)) -> ItemResponse:
return await item_service.get(db, item_id)
有關結構化、測試、安全性與 OpenAPI 文件的詳細指引,請參閱 FastAPI 領域技能:
.github/skills/python-fastapi-project-structuring/SKILL.md.github/skills/python-fastapi-routing-validation/SKILL.md.github/skills/python-fastapi-dependency-injection/SKILL.md.github/skills/python-fastapi-response-error-handling/SKILL.md.github/skills/python-fastapi-security-authentication/SKILL.md.github/skills/python-fastapi-security-attack-resistance/SKILL.md.github/skills/python-fastapi-api-testing/SKILL.md.github/skills/python-fastapi-openapi-documentation/SKILL.md
資料庫 — PostgreSQL + SQLAlchemy (非同步)
PostgreSQL 是唯一支援的資料庫。SQLAlchemy 是 ORM。
- 始終使用非同步引擎與 session (
AsyncEngine、AsyncSession)。 - 絕不在非同步程式碼中呼叫同步的 SQLAlchemy API。
- 使用
select()、insert()、update()、delete()(來自sqlalchemy)——而非原始 SQL 字串。 - 使用
async with AsyncSession(engine) as session管理 session 生命週期。 - 使用
DeclarativeBase定義模型;使用Mapped[T]型別化欄位註解(SQLAlchemy 2.x 風格)。
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
engine = create_async_engine("postgresql+asyncpg://...", echo=False)
class Base(DeclarativeBase):
pass
class Item(Base):
__tablename__ = "items"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
資料庫遷移 — Alembic
Alembic 管理所有 schema 變更。請勿手動修改資料庫 schema。
主要規則:
- 一旦套用至任何非本地環境,遷移即不可變更。
- 每個遷移在可能的情況下必須是冪等的。
- 所有 Alembic 指令都使用
uv run alembic。
uv run alembic revision --autogenerate -m "add_items_table"
uv run alembic upgrade head
uv run alembic history
uv run alembic current
有關完整的遷移撰寫規則與 RLS 強制執行,請參閱:
.github/skills/python-alembic-migrations/SKILL.md
如需重建僅限本地的遷移分支,請參閱:
.github/skills/python-alembic-migration-rebase/SKILL.md
非同步 — 始終使用
每個 I/O 操作必須是非同步的。請求路徑中不允許出現阻塞呼叫。
- 對於同時執行的獨立協程,使用
asyncio.gather()。 - 當需要結構化並發與錯誤傳播時(Python 3.11+),使用
asyncio.TaskGroup。 - 使用
asyncio.Queue或asyncio.Semaphore進行背壓與速率限制。 - 絕不呼叫
time.sleep()—— 應使用await asyncio.sleep()。 - 絕不使用
requests—— 應使用httpx.AsyncClient或aiohttp。
進階指引:
.github/skills/python-asyncio/asyncio-concurrent-web-requests/SKILL.md.github/skills/python-concurrent-processing/SKILL.md(CPU-bound 工作 ->ProcessPoolExecutor+ asyncio 整合).github/skills/python-asyncio/asyncio-synchronization/SKILL.md
函數式輕量風格
此程式碼庫採用「函數式輕量」方法:在能降低複雜度並提升清晰度的地方應用函數式技巧,但不會為了理論上的純粹性而強制執行。
我們要做的事
| 技巧 | 使用時機 |
|---|---|
| 純函數 | 業務邏輯的預設方式。除非必要,否則不應有副作用。 |
| 不可變資料 | 使用 frozen dataclass / Pydantic 模型作為值物件。 |
| 高階函數 | 在資料管道中偏好 map、filter、functools.reduce 而非命令式迴圈。 |
| 生成器 / 惰性序列 | 大型或串流資料集 — 避免在記憶體中建立完整的列表。 |
functools 工具 | 自由使用 lru_cache、cache、partial、wraps。 |
| 函數組合 | 在資料轉換管道中將小而集中的函數串聯起來。 |
| 描述性裝飾器 | 將橫切關注點(認證、快取、重試)表達為裝飾器。 |
我們不強制的事
| 技巧 | 除非明顯有益,否則避免的原因 |
|---|---|
Monad(Maybe、Either、Result) | 增加認知負擔;改用例外處理 + 型別化回傳值。 |
| Point-free 風格 | 對大多數團隊成員來說會降低可讀性。 |
| 處處強制不可變性 | SQLAlchemy 模型與非同步狀態本質上可變 — 只在必要的地方對抗它。 |
pymonad / returns 函式庫 | 僅限選擇性使用;未經團隊同意,不得強加於共享程式碼。 |
# ✅ 函數式輕量:專注純函數的管道
from functools import reduce
def parse_items(raw: list[dict]) -> list[Item]:
return [Item(**r) for r in raw if r.get("active")]
def enrich(item: Item, overrides: dict) -> Item:
return item.model_copy(update=overrides.get(item.id, {}))
def process(raw: list[dict], overrides: dict) -> list[Item]:
return [enrich(item, overrides) for item in parse_items(raw)]
進階指引 — 整合與專門的函數式技能:
.github/skills/python-higher-order-functools/SKILL.md(map, filter, max/min, @cache, partial, reduce, @singledispatch).github/skills/python-lazy-evaluation-pipelines/SKILL.md(yield, yield from, generator pipelines, map/filter/reduce).github/skills/python-immutable-data-design/SKILL.md(NamedTuple, frozen dataclass, pyrsistent, context managers).github/skills/python-functional-programming/python-decorator-design/SKILL.md.github/skills/python-functional-programming/python-functional-web-services/SKILL.md(FastAPI 函數式處理器).github/skills/python-functional-programming/python-toolz-composition/SKILL.md.github/skills/python-functional-programming/python-itertools-combinatorics/SKILL.md.github/skills/python-functional-programming/python-recursion-tco/SKILL.md.github/skills/python-functional-programming/python-pymonad-strict-evaluation/SKILL.md<- 僅限選擇性使用
通用程式碼慣例
- 最低要求 Python 3.11+。使用現代語法:
match、TypeAlias、Self等。 - 全面使用型別註解 — 函數簽名、變數、回傳型別。
- 不使用
Any,除非是與無型別的第三方邊界整合。 - 對於值物件,偏好使用
dataclass(frozen=True)或 PydanticBaseModel。 - 保持函數小而專一。如果一個函數需要註解來說明它做了什麼(而非為什麼這麼做),請將其拆分。
- 避免全域可變狀態。明確傳遞依賴項(透過建構函式或
Depends())。 - 使用
logging— 而非print。在應用程式啟動時配置;絕不要在函式庫程式碼中呼叫basicConfig()。 請參閱.github/skills/python-configuration-observability/SKILL.md以取得完整的日誌、追蹤與配置指引。
技能地圖
python/SKILL.md ← 您在此處 (主要參考)
│
├── 後端框架
│ ├── python-fastapi-project-structuring/SKILL.md
│ ├── python-fastapi-routing-validation/SKILL.md
│ ├── python-fastapi-dependency-injection/SKILL.md
│ ├── python-fastapi-response-error-handling/SKILL.md
│ ├── python-fastapi-security-authentication/SKILL.md
│ ├── python-fastapi-security-attack-resistance/SKILL.md
│ ├── python-fastapi-api-testing/SKILL.md
│ └── python-fastapi-openapi-documentation/SKILL.md
│
├── 資料庫與遷移
│ ├── python-alembic-migrations/SKILL.md
│ └── python-alembic-migration-rebase/SKILL.md
│
├── 非同步模式
│ ├── python-asyncio/asyncio-concurrent-web-requests/SKILL.md
│ └── python-asyncio/asyncio-synchronization/SKILL.md
│
├── 整合核心技能
│ ├── python-configuration-observability/SKILL.md (配置 + 日誌 + 追蹤)
│ ├── python-data-structures-type-system/SKILL.md (集合 + 型別 + Pydantic)
│ ├── python-lazy-evaluation-pipelines/SKILL.md (生成器 + map/filter/reduce)
│ ├── python-higher-order-functools/SKILL.md (HOFs + cache + partial + singledispatch)
│ ├── python-immutable-data-design/SKILL.md (NamedTuple + frozen DC + context mgrs)
│ └── python-concurrent-processing/SKILL.md (ProcessPool + asyncio 整合)
│
├── 函數式程式設計 (專門)
│ ├── python-functional-programming/python-decorator-design/SKILL.md
│ ├── python-functional-programming/python-functional-web-services/SKILL.md
│ ├── python-functional-programming/python-toolz-composition/SKILL.md
│ ├── python-functional-programming/python-itertools-combinatorics/SKILL.md
│ ├── python-functional-programming/python-recursion-tco/SKILL.md
│ └── python-functional-programming/python-pymonad-strict-evaluation/SKILL.md <- 選擇性
│
├── 函式庫建立
│ ├── python-library-creation/SKILL.md
│ └── python-project-setup/SKILL.md
│
├── Polars
│ ├── python-polars/SKILL.md
│ ├── python-polars-performance-tuning/SKILL.md
│ └── python-polars-integration/SKILL.md
│
├── 其他
│ ├── python-docker/SKILL.md
│ ├── python-git-workflow/SKILL.md
│ ├── python-testing-general/SKILL.md
│ ├── python-debugging/SKILL.md
│ └── python-performance-optimization/SKILL.md
相關技能
以下是本技能直接引用或延伸的其他領域技能:
核心技能
.github/skills/python-configuration-observability/SKILL.md— 使用 Dynaconf 與 logfire 進行配置、日誌與觀測性.github/skills/python-data-structures-type-system/SKILL.md— 資料結構(collections.abc)、型別系統與 Pydantic 模型.github/skills/python-lazy-evaluation-pipelines/SKILL.md— 生成器、yield from與 map/filter/reduce 惰性管道.github/skills/python-higher-order-functools/SKILL.md—map、filter、max/min、@cache、partial、reduce、@singledispatch.github/skills/python-immutable-data-design/SKILL.md— NamedTuple、frozen dataclass、pyrsistent、context managers.github/skills/python-concurrent-processing/SKILL.md— 使用ProcessPoolExecutor搭配 asyncio 進行 CPU-bound 並行處理
後端與 API
- 請參閱上方 FastAPI 技能
資料與資料庫
.github/skills/python-alembic-migrations/SKILL.md— 遷移撰寫、安全、RLS 與 CI 驗證.github/skills/python-alembic-migration-rebase/SKILL.md— 針對非套用分支的遷移壓縮與 rebase 工作流程
函數式程式設計
.github/skills/python-functional-programming/python-decorator-design/SKILL.md— 裝飾器模式與實作.github/skills/python-functional-programming/python-functional-web-services/SKILL.md— FastAPI 函數式處理器.github/skills/python-functional-programming/python-toolz-composition/SKILL.md— 使用 toolz 進行函數組合.github/skills/python-functional-programming/python-itertools-combinatorics/SKILL.md— 使用 itertools 進行迭代器組合.github/skills/python-functional-programming/python-recursion-tco/SKILL.md— 遞迴、尾遞迴最佳化與 trampolining.github/skills/python-functional-programming/python-pymonad-strict-evaluation/SKILL.md— 嚴格評估與 Monad(選擇性)