Python開発パターン
堅牢で効率的かつ保守可能なアプリケーションを構築するための慣用的なPythonパターンとベストプラクティス。
いつ有効化するか
- 新しいPythonコードを書くとき
- Pythonコードをレビューするとき
- 既存のPythonコードをリファクタリングするとき
- Pythonパッケージ/モジュールを設計するとき
核となる原則
1. 可読性が重要
Pythonは可読性を優先します。コードは明白で理解しやすいものであるべきです。
# Good: Clear and readable
def get_active_users(users: list[User]) -> list[User]:
"""Return only active users from the provided list."""
return [user for user in users if user.is_active]
# Bad: Clever but confusing
def get_active_users(u):
return [x for x in u if x.a]
2. 明示的は暗黙的より良い
魔法を避け、コードが何をしているかを明確にしましょう。
# Good: Explicit configuration
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Bad: Hidden side effects
import some_module
some_module.setup() # What does this do?
3. EAFP - 許可を求めるより許しを請う方が簡単
Pythonは条件チェックよりも例外処理を好みます。
# Good: EAFP style
def get_value(dictionary: dict, key: str, default_value: Any = None) -> Any:
try:
return dictionary[key]
except KeyError:
return default_value
# Bad: LBYL (Look Before You Leap) style
def get_value(dictionary: dict, key: str…