SKILL.md
readonlyread-only
name
python-patterns
description
Python 慣用寫法、PEP 8 標準、型別提示以及打造穩健、高效且易於維護的 Python 應用程式的最佳實務。
Python 開發模式
打造穩健、高效且易於維護的應用程式的慣用 Python 模式與最佳實務。
何時啟用
- 撰寫新的 Python 程式碼
- 審查 Python 程式碼
- 重構現有 Python 程式碼
- 設計 Python 套件/模組
核心原則
1. 可讀性至上
Python 優先考慮可讀性。程式碼應該清晰易懂。
# 好:清晰可讀
def get_active_users(users: list[User]) -> list[User]:
"""從提供的列表中僅回傳活躍使用者。"""
return [user for user in users if user.is_active]
# 壞:聰明但令人困惑
def get_active_users(u):
return [x for x in u if x.a]
2. 明確優於隱含
避免魔術;清楚說明你的程式碼在做什麼。
# 好:明確的設定
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# 壞:隱藏的副作用
import some_module
some_module.setup() # 這在做什麼?
3. EAFP - 請求原諒比取得許可容易
Python 偏好例外處理而非檢查條件。
# 好:EAFP 風格
def get_value(dictionary: dict, key: str, default_value: Any = None) -> Any:
try:
return dictionary[key]
except KeyError:
return default_value
# 壞:LBYL(先看再跳)風格
def get_value(dictionary: dict, key: str, default_value: Any = None) -> Any:
if key in dictionary:
return dictionary[key]
else:
return default_value
型別提示
基本型別註記
from typing import Optional, List, Dict, Any
def process_user(
user_id: str,
data: Dict[str, Any],
active: bool = True
) -> Optional[User]:
"""處理使用者並回傳更新後的 User 或 None。"""
if not active:
return None
return User(user_id, data)
現代型別提示(Python 3.9+)
# Python 3.9+ - 使用內建型別
def process_items(items: list[str]) -> dict[str, int]:
return {item: len(item) for item in items}
# Python 3.8 及更早版本 - 使用 typing 模組
from typing import List, Dict
def process_items(items: List[str]) -> Dict[str, int]:
return {item: len(item) for item in items}
型別別名與 TypeVar
from typing import TypeVar, Union
# 複雜型別的型別別名
JSON = Union[dict[str, Any], list[Any], str, int, float, bool, None]
def parse_json(data: str) -> JSON:
return json.loads(data)
# 泛型型別
T = TypeVar('T')
def first(items: list[T]) -> T | None:
"""回傳第一個項目,若清單為空則回傳 None。"""
return items[0] if items else None
基於協定的鴨子型別
from typing import Protocol
class Renderable(Protocol):
def render(self) -> str:
"""將物件渲染為字串。"""
def render_all(items: list[Renderable]) -> str:
"""渲染所有實作 Renderable 協定的項目。"""
return "\n".join(item.render() for item in items)
錯誤處理模式
特定例外處理
# 好:捕捉特定例外
def load_config(path: str) -> Config:
try:
with open(path) as f:
return Config.from_json(f.read())
except FileNotFoundError as e:
raise ConfigError(f"設定檔未找到:{path}") from e
except json.JSONDecodeError as e:
raise ConfigError(f"設定檔中的 JSON 無效:{path}") from e
# 壞:裸 except
def load_config(path: str) -> Config:
try:
with open(path) as f:
return Config.from_json(f.read())
except:
return None # 靜默失敗!
例外鏈結
def process_data(data: str) -> Result:
try:
parsed = json.loads(data)
except json.JSONDecodeError as e:
# 鏈結例外以保留追蹤
raise ValueError(f"無法解析資料:{data}") from e
自訂例外階層
class AppError(Exception):
"""所有應用程式錯誤的基礎例外。"""
pass
class ValidationError(AppError):
"""當輸入驗證失敗時拋出。"""
pass
class NotFoundError(AppError):
"""當請求的資源未找到時拋出。"""
pass
# 使用方式
def get_user(user_id: str) -> User:
user = db.find_user(user_id)
if not user:
raise NotFoundError(f"使用者未找到:{user_id}")
return user
情境管理器
資源管理
# 好:使用情境管理器
def process_file(path: str) -> str:
with open(path, 'r') as f:
return f.read()
# 壞:手動資源管理
def process_file(path: str) -> str:
f = open(path, 'r')
try:
return f.read()
finally:
f.close()
自訂情境管理器
from contextlib import contextmanager
@contextmanager
def timer(name: str):
"""用於計時一段程式碼的情境管理器。"""
start = time.perf_counter()
yield
elapsed = time.perf_counter() - start
print(f"{name} 花費 {elapsed:.4f} 秒")
# 使用方式
with timer("資料處理"):
process_large_dataset()
情境管理器類別
class DatabaseTransaction:
def __init__(self, connection):
self.connection = connection
def __enter__(self):
self.connection.begin_transaction()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self.connection.commit()
else:
self.connection.rollback()
return False # 不要壓制例外
# 使用方式
with DatabaseTransaction(conn):
user = conn.create_user(user_data)
conn.create_profile(user.id, profile_data)
推導式與生成器
串列推導式
# 好:用於簡單轉換的串列推導式
names = [user.name for user in users if user.is_active]
# 壞:手動迴圈
names = []
for user in users:
if user.is_active:
names.append(user.name)
# 複雜的推導式應展開
# 壞:過於複雜
result = [x * 2 for x in items if x > 0 if x % 2 == 0]
# 好:使用生成器函式
def filter_and_transform(items: Iterable[int]) -> list[int]:
result = []
for x in items:
if x > 0 and x % 2 == 0:
result.append(x * 2)
return result
生成器表達式
# 好:用於惰性求值的生成器
total = sum(x * x for x in range(1_000_000))
# 壞:建立大型中間串列
total = sum([x * x for x in range(1_000_000)])
生成器函式
def read_large_file(path: str) -> Iterator[str]:
"""逐行讀取大型檔案。"""
with open(path) as f:
for line in f:
yield line.strip()
# 使用方式
for line in read_large_file("huge.txt"):
process(line)
資料類別與具名元組
資料類別
from dataclasses import dataclass, field
from datetime import datetime
@dataclass
class User:
"""使用者實體,自動產生 __init__、__repr__ 和 __eq__。"""
id: str
name: str
email: str
created_at: datetime = field(default_factory=datetime.now)
is_active: bool = True
# 使用方式
user = User(
id="123",
name="Alice",
email="alice@example.com"
)
資料類別與驗證
@dataclass
class User:
email: str
age: int
def __post_init__(self):
# 驗證電子郵件格式
if "@" not in self.email:
raise ValueError(f"無效的電子郵件:{self.email}")
# 驗證年齡範圍
if self.age < 0 or self.age > 150:
raise ValueError(f"無效的年齡:{self.age}")
具名元組
from typing import NamedTuple
class Point(NamedTuple):
"""不可變的 2D 點。"""
x: float
y: float
def distance(self, other: 'Point') -> float:
return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
# 使用方式
p1 = Point(0, 0)
p2 = Point(3, 4)
print(p1.distance(p2)) # 5.0
裝飾器
函式裝飾器
import functools
import time
def timer(func: Callable) -> Callable:
"""用於計時函式執行的裝飾器。"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} 花費 {elapsed:.4f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
# slow_function() 印出:slow_function 花費 1.0012s
參數化裝飾器
def repeat(times: int):
"""用於重複執行函式多次的裝飾器。"""
def decorator(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args, **kwargs):
results = []
for _ in range(times):
results.append(func(*args, **kwargs))
return results
return wrapper
return decorator
@repeat(times=3)
def greet(name: str) -> str:
return f"Hello, {name}!"
# greet("Alice") 回傳 ["Hello, Alice!", "Hello, Alice!", "Hello, Alice!"]
基於類別的裝飾器
class CountCalls:
"""計算函式被呼叫次數的裝飾器。"""
def __init__(self, func: Callable):
functools.update_wrapper(self, func)
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
print(f"{self.func.__name__} 已被呼叫 {self.count} 次")
return self.func(*args, **kwargs)
@CountCalls
def process():
pass
# 每次呼叫 process() 都會印出呼叫次數
並行模式
用於 I/O 密集型任務的執行緒
import concurrent.futures
import threading
def fetch_url(url: str) -> str:
"""擷取 URL(I/O 密集型操作)。"""
import urllib.request
with urllib.request.urlopen(url) as response:
return response.read().decode()
def fetch_all_urls(urls: list[str]) -> dict[str, str]:
"""使用執行緒同時擷取多個 URL。"""
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
future_to_url = {executor.submit(fetch_url, url): url for url in urls}
results = {}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
results[url] = future.result()
except Exception as e:
results[url] = f"錯誤:{e}"
return results
用於 CPU 密集型任務的多重處理
def process_data(data: list[int]) -> int:
"""CPU 密集型計算。"""
return sum(x ** 2 for x in data)
def process_all(datasets: list[list[int]]) -> list[int]:
"""使用多個程序處理多個資料集。"""
with concurrent.futures.ProcessPoolExecutor() as executor:
results = list(executor.map(process_data, datasets))
return results
用於並行 I/O 的 Async/Await
import asyncio
async def fetch_async(url: str) -> str:
"""非同步擷取 URL。"""
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def fetch_all(urls: list[str]) -> dict[str, str]:
"""同時擷取多個 URL。"""
tasks = [fetch_async(url) for url in urls]
results = await asyncio.gather(*tasks, return_exceptions=True)
return dict(zip(urls, results))
套件組織
標準專案結構
myproject/
├── src/
│ └── mypackage/
│ ├── __init__.py
│ ├── main.py
│ ├── api/
│ │ ├── __init__.py
│ │ └── routes.py
│ ├── models/
│ │ ├── __init__.py
│ │ └── user.py
│ └── utils/
│ ├── __init__.py
│ └── helpers.py
├── tests/
│ ├── __init__.py
│ ├── conftest.py
│ ├── test_api.py
│ └── test_models.py
├── pyproject.toml
├── README.md
└── .gitignore
匯入慣例
# 好:匯入順序 - 標準函式庫、第三方、本地
import os
import sys
from pathlib import Path
import requests
from fastapi import FastAPI
from mypackage.models import User
from mypackage.utils import format_name
# 好:使用 isort 自動排序匯入
# pip install isort
用於套件匯出的 init.py
# mypackage/__init__.py
"""mypackage - 一個範例 Python 套件。"""
__version__ = "1.0.0"
# 在套件層級匯出主要類別/函式
from mypackage.models import User, Post
from mypackage.utils import format_name
__all__ = ["User", "Post", "format_name"]
記憶體與效能
使用 slots 提升記憶體效率
# 壞:一般類別使用 __dict__(較多記憶體)
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
# 好:__slots__ 減少記憶體使用
class Point:
__slots__ = ['x', 'y']
def __init__(self, x: float, y: float):
self.x = x
self.y = y
用於大型資料的生成器
# 壞:在記憶體中回傳完整串列
def read_lines(path: str) -> list[str]:
with open(path) as f:
return [line.strip() for line in f]
# 好:一次產生一行
def read_lines(path: str) -> Iterator[str]:
with open(path) as f:
for line in f:
yield line.strip()
避免在迴圈中串接字串
# 壞:O(n²) 由於字串不可變性
result = ""
for item in items:
result += str(item)
# 好:使用 join 為 O(n)
result = "".join(str(item) for item in items)
# 好:使用 StringIO 建構
from io import StringIO
buffer = StringIO()
for item in items:
buffer.write(str(item))
result = buffer.getvalue()
Python 工具整合
基本指令
# 程式碼格式化
black .
isort .
# 語法檢查
ruff check .
pylint mypackage/
# 型別檢查
mypy .
# 測試
pytest --cov=mypackage --cov-report=html
# 安全掃描
bandit -r .
# 相依性管理
pip-audit
safety check
pyproject.toml 設定
[project]
name = "mypackage"
version = "1.0.0"
requires-python = ">=3.9"
dependencies = [
"requests>=2.31.0",
"pydantic>=2.0.0",
]
[project.optional-dependencies]
dev = [
"pytest>=7.4.0",
"pytest-cov>=4.1.0",
"black>=23.0.0",
"ruff>=0.1.0",
"mypy>=1.5.0",
]
[tool.black]
line-length = 88
target-version = ['py39']
[tool.ruff]
line-length = 88
select = ["E", "F", "I", "N", "W"]
[tool.mypy]
python_version = "3.9"
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "--cov=mypackage --cov-report=term-missing"
快速參考:Python 慣用寫法
| 慣用寫法 | 說明 |
|---|---|
| EAFP | 請求原諒比取得許可容易 |
| 情境管理器 | 使用 with 進行資源管理 |
| 串列推導式 | 用於簡單轉換 |
| 生成器 | 用於惰性求值和大型資料集 |
| 型別提示 | 註記函式簽名 |
| 資料類別 | 用於自動產生方法的資料容器 |
__slots__ |
用於記憶體最佳化 |
| f-string | 用於字串格式化(Python 3.6+) |
pathlib.Path |
用於路徑操作(Python 3.4+) |
enumerate |
用於迴圈中的索引-元素配對 |
應避免的反模式
# 壞:可變的預設引數
def append_to(item, items=[]):
items.append(item)
return items
# 好:使用 None 並建立新串列
def append_to(item, items=None):
if items is None:
items = []
items.append(item)
return items
# 壞:使用 type() 檢查型別
if type(obj) == list:
process(obj)
# 好:使用 isinstance
if isinstance(obj, list):
process(obj)
# 壞:使用 == 比較 None
if value == None:
process()
# 好:使用 is
if value is None:
process()
# 壞:from module import *
from os.path import *
# 好:明確匯入
from os.path import join, exists
# 壞:裸 except
try:
risky_operation()
except:
pass
# 好:特定例外
try:
risky_operation()
except SpecificError as e:
logger.error(f"操作失敗:{e}")
記住:Python 程式碼應可讀、明確,並遵循最小驚訝原則。有疑問時,優先考慮清晰而非聰明。






