python-anti-patterns について
コードレビュー、デバッグ、リファクタリングに使える、Python のアンチパターンチェックリストです。問題を分野別に整理し、改善方法も示します。
主な機能
- 01インフラと設定の問題を確認
- 02設計とエラー処理の問題を発見
- 03リソースと非同期処理を確認
- 04型ヒントとコレクション型を確認
- 05エラー経路と境界値をテスト
活用シーン
- 01マージ前の Python コードレビュー
- 02原因不明の動作の調査
- 03レガシーコードのリファクタリング
- 04チームのコーディング規約策定
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ wshobson/ agents --skill python-anti-patternsインストール後、Claude Code で/python-anti-patternsを入力して読み込まれたか確認します。
詳細
Python アンチパターンチェックリスト
Python コードでよくある間違いとアンチパターンのリファレンスチェックリストです。実装を確定する前にこれを確認し、問題を早期に発見しましょう。
このスキルを使う場面
- マージ前のコードレビュー
- 原因不明の問題のデバッグ
- Python のベストプラクティスの指導や学習
- チームのコーディング標準の策定
- レガシーコードのリファクタリング
注意: このスキルは避けるべきことに焦点を当てています。推奨されるパターンとアーキテクチャのガイダンスについては、python-design-patterns スキルを参照してください。
インフラストラクチャのアンチパターン
散在するタイムアウト/リトライロジック
# BAD: Timeout logic duplicated everywhere
def fetch_user(user_id):
try:
return requests.get(url, timeout=30)
except Timeout:
logger.warning("Timeout fetching user")
return None
def fetch_orders(user_id):
try:
return requests.get(url, timeout=30)
except Timeout:
logger.warning("Timeout fetching orders")
return None
修正: デコレーターまたはクライアントラッパーに集約します。
# GOOD: Centralized retry logic
@retry(stop=stop_after_attempt(3), wait=wait_exponential())
def http_get(url: str) -> Response:
return requests.get(url, timeout=30)
二重リトライ
# BAD: Retrying at multiple layers
@retry(max_attempts=3) # Application retry
def call_service():
return client.request() # Client also has retry configured!
修正: リトライは 1 つのレイヤーでのみ行います。自分のインフラストラクチャのリトライ動作を把握しておきましょう。
ハードコードされた設定
# BAD: Secrets and config in code
DB_HOST = "prod-db.example.com"
API_KEY = "sk-12345"
def connect():
return psycopg.connect(f"host={DB_HOST}...")
修正: 型付き設定で環境変数を使用します。
# GOOD
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
db_host: str = Field(alias="DB_HOST")
api_key: str = Field(alias="API_KEY")
settings = Settings()
アーキテクチャのアンチパターン
内部型の露出
# BAD: Leaking ORM model to API
@app.get("/users/{id}")
def get_user(id: str) -> UserModel: # SQLAlchemy model
return db.query(UserModel).get(id)
修正: DTO/レスポンスモデルを使用します。
# GOOD
@app.get("/users/{id}")
def get_user(id: str) -> UserResponse:
user = db.query(UserModel).get(id)
return UserResponse.from_orm(user)
I/O とビジネスロジックの混在
# BAD: SQL embedded in business logic
def calculate_discount(user_id: str) -> float:
user = db.query("SELECT * FROM users WHERE id = ?", user_id)
orders = db.query("SELECT * FROM orders WHERE user_id = ?", user_id)
# Business logic mixed with data access
if len(orders) > 10:
return 0.15
return 0.0
修正: リポジトリパターン。ビジネスロジックは純粋に保ちます。
# GOOD
def calculate_discount(user: User, orders: list[Order]) -> float:
# Pure business logic, easily testable
if len(orders) > 10:
return 0.15
return 0.0
エラーハンドリングのアンチパターン
裸の例外処理
# BAD: Swallowing all exceptions
try:
process()
except Exception:
pass # Silent failure - bugs hidden forever
修正: 特定の例外を捕捉します。適切にログを記録するか処理します。
# GOOD
try:
process()
except ConnectionError as e:
logger.warning("Connection failed, will retry", error=str(e))
raise
except ValueError as e:
logger.error("Invalid input", error=str(e))
raise BadRequestError(str(e))
部分的な失敗の無視
# BAD: Stops on first error
def process_batch(items):
results = []
for item in items:
result = process(item) # Raises on error - batch aborted
results.append(result)
return results
修正: 成功と失敗の両方を取得します。
# GOOD
def process_batch(items) -> BatchResult:
succeeded = {}
failed = {}
for idx, item in enumerate(items):
try:
succeeded[idx] = process(item)
except Exception as e:
failed[idx] = e
return BatchResult(succeeded, failed)
入力バリデーションの欠如
# BAD: No validation
def create_user(data: dict):
return User(**data) # Crashes deep in code on bad input
修正: API 境界で早期にバリデーションを行います。
# GOOD
def create_user(data: dict) -> User:
validated = CreateUserInput.model_validate(data)
return User.from_input(validated)
リソースのアンチパターン
クローズされないリソース
# BAD: File never closed
def read_file(path):
f = open(path)
return f.read() # What if this raises?
修正: コンテキストマネージャーを使用します。
# GOOD
def read_file(path):
with open(path) as f:
return f.read()
非同期処理でのブロッキング
# BAD: Blocks the entire event loop
async def fetch_data():
time.sleep(1) # Blocks everything!
response = requests.get(url) # Also blocks!
修正: 非同期ネイティブのライブラリを使用します。
# GOOD
async def fetch_data():
await asyncio.sleep(1)
async with httpx.AsyncClient() as client:
response = await client.get(url)
型安全性のアンチパターン
型ヒントの欠如
# BAD: No types
def process(data):
return data["value"] * 2
修正: すべての公開関数に型アノテーションを付けます。
# GOOD
def process(data: dict[str, int]) -> int:
return data["value"] * 2
型付けされていないコレクション
# BAD: Generic list without type parameter
def get_users() -> list:
...
修正: 型パラメーターを使用します。
# GOOD
def get_users() -> list[User]:
...
テストのアンチパターン
ハッピーパスしかテストしない
# BAD: Only tests success case
def test_create_user():
user = service.create_user(valid_data)
assert user.id is not None
修正: エラー条件とエッジケースをテストします。
# GOOD
def test_create_user_success():
user = service.create_user(valid_data)
assert user.id is not None
def test_create_user_invalid_email():
with pytest.raises(ValueError, match="Invalid email"):
service.create_user(invalid_email_data)
def test_create_user_duplicate_email():
service.create_user(valid_data)
with pytest.raises(ConflictError):
service.create_user(valid_data)
過剰なモック
# BAD: Mocking everything
def test_user_service():
mock_repo = Mock()
mock_cache = Mock()
mock_logger = Mock()
mock_metrics = Mock()
# Test doesn't verify real behavior
修正: 重要なパスには統合テストを使用します。モックするのは外部サービスのみにします。
クイックレビューチェックリスト
コードを確定する前に、以下を確認してください:
- 散在するタイムアウト/リトライロジックがない(集約されている)
- 二重リトライがない(アプリ + インフラストラクチャ)
- ハードコードされた設定やシークレットがない
- 内部型(ORM モデル、protobuf)が露出していない
- I/O とビジネスロジックが混在していない
- 裸の
except Exception: passがない - バッチ内の部分的な失敗を無視していない
- 入力バリデーションの欠如がない
- クローズされないリソースがない(コンテキストマネージャーを使用している)
- 非同期コード内にブロッキング呼び出しがない
- すべての公開関数に型ヒントがある
- コレクションに型パラメーターがある
- エラーパスがテストされている
- エッジケースがカバーされている
よくある修正のまとめ
| アンチパターン | 修正 |
|---|---|
| 散在するリトライロジック | 集約されたデコレーター |
| ハードコードされた設定 | 環境変数 + pydantic-settings |
| ORM モデルの露出 | DTO/レスポンススキーマ |
| I/O とロジックの混在 | リポジトリパターン |
| 裸の except | 特定の例外を捕捉 |
| エラーでバッチが停止 | 成功/失敗を含む BatchResult を返す |
| バリデーションなし | Pydantic で境界でバリデーション |
| クローズされないリソース | コンテキストマネージャー |
| 非同期でのブロッキング | 非同期ネイティブのライブラリ |
| 型の欠如 | すべての公開 API に型アノテーション |
| ハッピーパスのテストのみ | エラーとエッジケースをテスト |
コメント
Markdown 対応