[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72ZP8W6YY2AH58DY0S2MMRH":3,"skill-same:01M72ZP8W6YY2AH58DY0S2MMRH":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M72ZP8W6YY2AH58DY0S2MMRH","python-patterns",null,"Pythonic イディオム、PEP 8標準、型ヒント、堅牢で効率的かつ保守可能なPythonアプリケーションを構築するためのベストプラクティス。","SriramGandhiS\u002FSkills","SriramGandhiS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211849986?v=4","01M72WQCW12BYX71C6WN584TTA","Sriram S","01M72WQCWTJ2RD0ET1X31AF1RC",1,"MIT","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fskills\u002Feverything-claude-code\u002Fdocs\u002Fja-JP\u002Fskills\u002Fpython-patterns\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: python-patterns\ndescription: Pythonic イディオム、PEP 8標準、型ヒント、堅牢で効率的かつ保守可能なPythonアプリケーションを構築するためのベストプラクティス。\n---\n\n# Python開発パターン\n\n堅牢で効率的かつ保守可能なアプリケーションを構築するための慣用的なPythonパターンとベストプラクティス。\n\n## いつ有効化するか\n\n- 新しいPythonコードを書くとき\n- Pythonコードをレビューするとき\n- 既存のPythonコードをリファクタリングするとき\n- Pythonパッケージ\u002Fモジュールを設計するとき\n\n## 核となる原則\n\n### 1. 可読性が重要\n\nPythonは可読性を優先します。コードは明白で理解しやすいものであるべきです。\n\n```python\n# Good: Clear and readable\ndef get_active_users(users: list[User]) -> list[User]:\n    \"\"\"Return only active users from the provided list.\"\"\"\n    return [user for user in users if user.is_active]\n\n# Bad: Clever but confusing\ndef get_active_users(u):\n    return [x for x in u if x.a]\n```\n\n### 2. 明示的は暗黙的より良い\n\n魔法を避け、コードが何をしているかを明確にしましょう。\n\n```python\n# Good: Explicit configuration\nimport logging\n\nlogging.basicConfig(\n    level=logging.INFO,\n    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n)\n\n# Bad: Hidden side effects\nimport some_module\nsome_module.setup()  # What does this do?\n```\n\n### 3. EAFP - 許可を求めるより許しを請う方が簡単\n\nPythonは条件チェックよりも例外処理を好みます。\n\n```python\n# Good: EAFP style\ndef get_value(dictionary: dict, key: str) -> Any:\n    try:\n        return dictionary[key]\n    except KeyError:\n        return default_value\n\n# Bad: LBYL (Look Before You Leap) style\ndef get_value(dictionary: dict, key: str) -> Any:\n    if key in dictionary:\n        return dictionary[key]\n    else:\n        return default_value\n```\n\n## 型ヒント\n\n### 基本的な型アノテーション\n\n```python\nfrom typing import Optional, List, Dict, Any\n\ndef process_user(\n    user_id: str,\n    data: Dict[str, Any],\n    active: bool = True\n) -> Optional[User]:\n    \"\"\"Process a user and return the updated User or None.\"\"\"\n    if not active:\n        return None\n    return User(user_id, data)\n```\n\n### モダンな型ヒント（Python 3.9+）\n\n```python\n# Python 3.9+ - Use built-in types\ndef process_items(items: list[str]) -> dict[str, int]:\n    return {item: len(item) for item in items}\n\n# Python 3.8 and earlier - Use typing module\nfrom typing import List, Dict\n\ndef process_items(items: List[str]) -> Dict[str, int]:\n    return {item: len(item) for item in items}\n```\n\n### 型エイリアスとTypeVar\n\n```python\nfrom typing import TypeVar, Union\n\n# Type alias for complex types\nJSON = Union[dict[str, Any], list[Any], str, int, float, bool, None]\n\ndef parse_json(data: str) -> JSON:\n    return json.loads(data)\n\n# Generic types\nT = TypeVar('T')\n\ndef first(items: list[T]) -> T | None:\n    \"\"\"Return the first item or None if list is empty.\"\"\"\n    return items[0] if items else None\n```\n\n### プロトコルベースのダックタイピング\n\n```python\nfrom typing import Protocol\n\nclass Renderable(Protocol):\n    def render(self) -> str:\n        \"\"\"Render the object to a string.\"\"\"\n\ndef render_all(items: list[Renderable]) -> str:\n    \"\"\"Render all items that implement the Renderable protocol.\"\"\"\n    return \"\\n\".join(item.render() for item in items)\n```\n\n## エラーハンドリングパターン\n\n### 特定の例外処理\n\n```python\n# Good: Catch specific exceptions\ndef load_config(path: str) -> Config:\n    try:\n        with open(path) as f:\n            return Config.from_json(f.read())\n    except FileNotFoundError as e:\n        raise ConfigError(f\"Config file not found: {path}\") from e\n    except json.JSONDecodeError as e:\n        raise ConfigError(f\"Invalid JSON in config: {path}\") from e\n\n# Bad: Bare except\ndef load_config(path: str) -> Config:\n    try:\n        with open(path) as f:\n            return Config.from_json(f.read())\n    except:\n        return None  # Silent failure!\n```\n\n### 例外の連鎖\n\n```python\ndef process_data(data: str) -> Result:\n    try:\n        parsed = json.loads(data)\n    except json.JSONDecodeError as e:\n        # Chain exceptions to preserve the traceback\n        raise ValueError(f\"Failed to parse data: {data}\") from e\n```\n\n### カスタム例外階層\n\n```python\nclass AppError(Exception):\n    \"\"\"Base exception for all application errors.\"\"\"\n    pass\n\nclass ValidationError(AppError):\n    \"\"\"Raised when input validation fails.\"\"\"\n    pass\n\nclass NotFoundError(AppError):\n    \"\"\"Raised when a requested resource is not found.\"\"\"\n    pass\n\n# Usage\ndef get_user(user_id: str) -> User:\n    user = db.find_user(user_id)\n    if not user:\n        raise NotFoundError(f\"User not found: {user_id}\")\n    return user\n```\n\n## コンテキストマネージャ\n\n### リソース管理\n\n```python\n# Good: Using context managers\ndef process_file(path: str) -> str:\n    with open(path, 'r') as f:\n        return f.read()\n\n# Bad: Manual resource management\ndef process_file(path: str) -> str:\n    f = open(path, 'r')\n    try:\n        return f.read()\n    finally:\n        f.close()\n```\n\n### カスタムコンテキストマネージャ\n\n```python\nfrom contextlib import contextmanager\n\n@contextmanager\ndef timer(name: str):\n    \"\"\"Context manager to time a block of code.\"\"\"\n    start = time.perf_counter()\n    yield\n    elapsed = time.perf_counter() - start\n    print(f\"{name} took {elapsed:.4f} seconds\")\n\n# Usage\nwith timer(\"data processing\"):\n    process_large_dataset()\n```\n\n### コンテキストマネージャクラス\n\n```python\nclass DatabaseTransaction:\n    def __init__(self, connection):\n        self.connection = connection\n\n    def __enter__(self):\n        self.connection.begin_transaction()\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        if exc_type is None:\n            self.connection.commit()\n        else:\n            self.connection.rollback()\n        return False  # Don't suppress exceptions\n\n# Usage\nwith DatabaseTransaction(conn):\n    user = conn.create_user(user_data)\n    conn.create_profile(user.id, profile_data)\n```\n\n## 内包表記とジェネレータ\n\n### リスト内包表記\n\n```python\n# Good: List comprehension for simple transformations\nnames = [user.name for user in users if user.is_active]\n\n# Bad: Manual loop\nnames = []\nfor user in users:\n    if user.is_active:\n        names.append(user.name)\n\n# Complex comprehensions should be expanded\n# Bad: Too complex\nresult = [x * 2 for x in items if x > 0 if x % 2 == 0]\n\n# Good: Use a generator function\ndef filter_and_transform(items: Iterable[int]) -> list[int]:\n    result = []\n    for x in items:\n        if x > 0 and x % 2 == 0:\n            result.append(x * 2)\n    return result\n```\n\n### ジェネレータ式\n\n```python\n# Good: Generator for lazy evaluation\ntotal = sum(x * x for x in range(1_000_000))\n\n# Bad: Creates large intermediate list\ntotal = sum([x * x for x in range(1_000_000)])\n```\n\n### ジェネレータ関数\n\n```python\ndef read_large_file(path: str) -> Iterator[str]:\n    \"\"\"Read a large file line by line.\"\"\"\n    with open(path) as f:\n        for line in f:\n            yield line.strip()\n\n# Usage\nfor line in read_large_file(\"huge.txt\"):\n    process(line)\n```\n\n## データクラスと名前付きタプル\n\n### データクラス\n\n```python\nfrom dataclasses import dataclass, field\nfrom datetime import datetime\n\n@dataclass\nclass User:\n    \"\"\"User entity with automatic __init__, __repr__, and __eq__.\"\"\"\n    id: str\n    name: str\n    email: str\n    created_at: datetime = field(default_factory=datetime.now)\n    is_active: bool = True\n\n# Usage\nuser = User(\n    id=\"123\",\n    name=\"Alice\",\n    email=\"alice@example.com\"\n)\n```\n\n### バリデーション付きデータクラス\n\n```python\n@dataclass\nclass User:\n    email: str\n    age: int\n\n    def __post_init__(self):\n        # Validate email format\n        if \"@\" not in self.email:\n            raise ValueError(f\"Invalid email: {self.email}\")\n        # Validate age range\n        if self.age \u003C 0 or self.age > 150:\n            raise ValueError(f\"Invalid age: {self.age}\")\n```\n\n### 名前付きタプル\n\n```python\nfrom typing import NamedTuple\n\nclass Point(NamedTuple):\n    \"\"\"Immutable 2D point.\"\"\"\n    x: float\n    y: float\n\n    def distance(self, other: 'Point') -> float:\n        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5\n\n# Usage\np1 = Point(0, 0)\np2 = Point(3, 4)\nprint(p1.distance(p2))  # 5.0\n```\n\n## デコレータ\n\n### 関数デコレータ\n\n```python\nimport functools\nimport time\n\ndef timer(func: Callable) -> Callable:\n    \"\"\"Decorator to time function execution.\"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        start = time.perf_counter()\n        result = func(*args, **kwargs)\n        elapsed = time.perf_counter() - start\n        print(f\"{func.__name__} took {elapsed:.4f}s\")\n        return result\n    return wrapper\n\n@timer\ndef slow_function():\n    time.sleep(1)\n\n# slow_function() prints: slow_function took 1.0012s\n```\n\n### パラメータ化デコレータ\n\n```python\ndef repeat(times: int):\n    \"\"\"Decorator to repeat a function multiple times.\"\"\"\n    def decorator(func: Callable) -> Callable:\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            results = []\n            for _ in range(times):\n                results.append(func(*args, **kwargs))\n            return results\n        return wrapper\n    return decorator\n\n@repeat(times=3)\ndef greet(name: str) -> str:\n    return f\"Hello, {name}!\"\n\n# greet(\"Alice\") returns [\"Hello, Alice!\", \"Hello, Alice!\", \"Hello, Alice!\"]\n```\n\n### クラスベースのデコレータ\n\n```python\nclass CountCalls:\n    \"\"\"Decorator that counts how many times a function is called.\"\"\"\n    def __init__(self, func: Callable):\n        functools.update_wrapper(self, func)\n        self.func = func\n        self.count = 0\n\n    def __call__(self, *args, **kwargs):\n        self.count += 1\n        print(f\"{self.func.__name__} has been called {self.count} times\")\n        return self.func(*args, **kwargs)\n\n@CountCalls\ndef process():\n    pass\n\n# Each call to process() prints the call count\n```\n\n## 並行処理パターン\n\n### I\u002FOバウンドタスク用のスレッド\n\n```python\nimport concurrent.futures\nimport threading\n\ndef fetch_url(url: str) -> str:\n    \"\"\"Fetch a URL (I\u002FO-bound operation).\"\"\"\n    import urllib.request\n    with urllib.request.urlopen(url) as response:\n        return response.read().decode()\n\ndef fetch_all_urls(urls: list[str]) -> dict[str, str]:\n    \"\"\"Fetch multiple URLs concurrently using threads.\"\"\"\n    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:\n        future_to_url = {executor.submit(fetch_url, url): url for url in urls}\n        results = {}\n        for future in concurrent.futures.as_completed(future_to_url):\n            url = future_to_url[future]\n            try:\n                results[url] = future.result()\n            except Exception as e:\n                results[url] = f\"Error: {e}\"\n    return results\n```\n\n### CPUバウンドタスク用のマルチプロセシング\n\n```python\ndef process_data(data: list[int]) -> int:\n    \"\"\"CPU-intensive computation.\"\"\"\n    return sum(x ** 2 for x in data)\n\ndef process_all(datasets: list[list[int]]) -> list[int]:\n    \"\"\"Process multiple datasets using multiple processes.\"\"\"\n    with concurrent.futures.ProcessPoolExecutor() as executor:\n        results = list(executor.map(process_data, datasets))\n    return results\n```\n\n### 並行I\u002FO用のAsync\u002FAwait\n\n```python\nimport asyncio\n\nasync def fetch_async(url: str) -> str:\n    \"\"\"Fetch a URL asynchronously.\"\"\"\n    import aiohttp\n    async with aiohttp.ClientSession() as session:\n        async with session.get(url) as response:\n            return await response.text()\n\nasync def fetch_all(urls: list[str]) -> dict[str, str]:\n    \"\"\"Fetch multiple URLs concurrently.\"\"\"\n    tasks = [fetch_async(url) for url in urls]\n    results = await asyncio.gather(*tasks, return_exceptions=True)\n    return dict(zip(urls, results))\n```\n\n## パッケージ構成\n\n### 標準プロジェクトレイアウト\n\n```\nmyproject\u002F\n├── src\u002F\n│   └── mypackage\u002F\n│       ├── __init__.py\n│       ├── main.py\n│       ├── api\u002F\n│       │   ├── __init__.py\n│       │   └── routes.py\n│       ├── models\u002F\n│       │   ├── __init__.py\n│       │   └── user.py\n│       └── utils\u002F\n│           ├── __init__.py\n│           └── helpers.py\n├── tests\u002F\n│   ├── __init__.py\n│   ├── conftest.py\n│   ├── test_api.py\n│   └── test_models.py\n├── pyproject.toml\n├── README.md\n└── .gitignore\n```\n\n### インポート規約\n\n```python\n# Good: Import order - stdlib, third-party, local\nimport os\nimport sys\nfrom pathlib import Path\n\nimport requests\nfrom fastapi import FastAPI\n\nfrom mypackage.models import User\nfrom mypackage.utils import format_name\n\n# Good: Use isort for automatic import sorting\n# pip install isort\n```\n\n### パッケージエクスポート用の__init__.py\n\n```python\n# mypackage\u002F__init__.py\n\"\"\"mypackage - A sample Python package.\"\"\"\n\n__version__ = \"1.0.0\"\n\n# Export main classes\u002Ffunctions at package level\nfrom mypackage.models import User, Post\nfrom mypackage.utils import format_name\n\n__all__ = [\"User\", \"Post\", \"format_name\"]\n```\n\n## メモリとパフォーマンス\n\n### メモリ効率化のための__slots__使用\n\n```python\n# Bad: Regular class uses __dict__ (more memory)\nclass Point:\n    def __init__(self, x: float, y: float):\n        self.x = x\n        self.y = y\n\n# Good: __slots__ reduces memory usage\nclass Point:\n    __slots__ = ['x', 'y']\n\n    def __init__(self, x: float, y: float):\n        self.x = x\n        self.y = y\n```\n\n### 大量データ用のジェネレータ\n\n```python\n# Bad: Returns full list in memory\ndef read_lines(path: str) -> list[str]:\n    with open(path) as f:\n        return [line.strip() for line in f]\n\n# Good: Yields lines one at a time\ndef read_lines(path: str) -> Iterator[str]:\n    with open(path) as f:\n        for line in f:\n            yield line.strip()\n```\n\n### ループ内での文字列連結を避ける\n\n```python\n# Bad: O(n²) due to string immutability\nresult = \"\"\nfor item in items:\n    result += str(item)\n\n# Good: O(n) using join\nresult = \"\".join(str(item) for item in items)\n\n# Good: Using StringIO for building\nfrom io import StringIO\n\nbuffer = StringIO()\nfor item in items:\n    buffer.write(str(item))\nresult = buffer.getvalue()\n```\n\n## Pythonツール統合\n\n### 基本コマンド\n\n```bash\n# Code formatting\nblack .\nisort .\n\n# Linting\nruff check .\npylint mypackage\u002F\n\n# Type checking\nmypy .\n\n# Testing\npytest --cov=mypackage --cov-report=html\n\n# Security scanning\nbandit -r .\n\n# Dependency management\npip-audit\nsafety check\n```\n\n### pyproject.toml設定\n\n```toml\n[project]\nname = \"mypackage\"\nversion = \"1.0.0\"\nrequires-python = \">=3.9\"\ndependencies = [\n    \"requests>=2.31.0\",\n    \"pydantic>=2.0.0\",\n]\n\n[project.optional-dependencies]\ndev = [\n    \"pytest>=7.4.0\",\n    \"pytest-cov>=4.1.0\",\n    \"black>=23.0.0\",\n    \"ruff>=0.1.0\",\n    \"mypy>=1.5.0\",\n]\n\n[tool.black]\nline-length = 88\ntarget-version = ['py39']\n\n[tool.ruff]\nline-length = 88\nselect = [\"E\", \"F\", \"I\", \"N\", \"W\"]\n\n[tool.mypy]\npython_version = \"3.9\"\nwarn_return_any = true\nwarn_unused_configs = true\ndisallow_untyped_defs = true\n\n[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\naddopts = \"--cov=mypackage --cov-report=term-missing\"\n```\n\n## クイックリファレンス：Pythonイディオム\n\n| イディオム | 説明 |\n|-------|-------------|\n| EAFP | 許可を求めるより許しを請う方が簡単 |\n| コンテキストマネージャ | リソース管理には`with`を使用 |\n| リスト内包表記 | 簡単な変換用 |\n| ジェネレータ | 遅延評価と大規模データセット用 |\n| 型ヒント | 関数シグネチャへのアノテーション |\n| データクラス | 自動生成メソッド付きデータコンテナ用 |\n| `__slots__` | メモリ最適化用 |\n| f-strings | 文字列フォーマット用（Python 3.6+） |\n| `pathlib.Path` | パス操作用（Python 3.4+） |\n| `enumerate` | ループ内のインデックス-要素ペア用 |\n\n## 避けるべきアンチパターン\n\n```python\n# Bad: Mutable default arguments\ndef append_to(item, items=[]):\n    items.append(item)\n    return items\n\n# Good: Use None and create new list\ndef append_to(item, items=None):\n    if items is None:\n        items = []\n    items.append(item)\n    return items\n\n# Bad: Checking type with type()\nif type(obj) == list:\n    process(obj)\n\n# Good: Use isinstance\nif isinstance(obj, list):\n    process(obj)\n\n# Bad: Comparing to None with ==\nif value == None:\n    process()\n\n# Good: Use is\nif value is None:\n    process()\n\n# Bad: from module import *\nfrom os.path import *\n\n# Good: Explicit imports\nfrom os.path import join, exists\n\n# Bad: Bare except\ntry:\n    risky_operation()\nexcept:\n    pass\n\n# Good: Specific exception\ntry:\n    risky_operation()\nexcept SpecificError as e:\n    logger.error(f\"Operation failed: {e}\")\n```\n\n**覚えておいてください**: Pythonコードは読みやすく、明示的で、最小の驚きの原則に従うべきです。迷ったときは、巧妙さよりも明確さを優先してください。\n","# Python開発パターン\n\n堅牢で効率的かつ保守可能なアプリケーションを構築するための慣用的なPythonパターンとベストプラクティス。\n\n## いつ有効化するか\n\n- 新しいPythonコードを書くとき\n- Pythonコードをレビューするとき\n- 既存のPythonコードをリファクタリングするとき\n- Pythonパッケージ\u002Fモジュールを設計するとき\n\n## 核となる原則\n\n### 1. 可読性が重要\n\nPythonは可読性を優先します。コードは明白で理解しやすいものであるべきです。\n\n```python\n# Good: Clear and readable\ndef get_active_users(users: list[User]) -> list[User]:\n    \"\"\"Return only active users from the provided list.\"\"\"\n    return [user for user in users if user.is_active]\n\n# Bad: Clever but confusing\ndef get_active_users(u):\n    return [x for x in u if x.a]\n```\n\n### 2. 明示的は暗黙的より良い\n\n魔法を避け、コードが何をしているかを明確にしましょう。\n\n```python\n# Good: Explicit configuration\nimport logging\n\nlogging.basicConfig(\n    level=logging.INFO,\n    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n)\n\n# Bad: Hidden side effects\nimport some_module\nsome_module.setup()  # What does this do?\n```\n\n### 3. EAFP - 許可を求めるより許しを請う方が簡単\n\nPythonは条件チェックよりも例外処理を好みます。\n\n```python\n# Good: EAFP style\ndef get_value(dictionary: dict, key: str) -> Any:\n    try:\n        return dictionary[key]\n    except KeyError:\n        return default_value\n\n# Bad: LBYL (Look Before You Leap) style\ndef get_value(dictionary: dict, key: str) -> Any:\n    if key in dictionary:\n        return dictionary[key]\n    else:\n        return default_value\n```\n\n## 型ヒント\n\n### 基本的な型アノテーション\n\n```python\nfrom typing import Optional, List, Dict, Any\n\ndef process_user(\n    user_id: str,\n    data: Dict[str, Any],\n    active: bool = True\n) -> Optional[User]:\n    \"\"\"Process a user and return the updated User or None.\"\"\"\n    if not active:\n        return None\n    return User(user_id, data)\n```\n\n### モダンな型ヒント（Python 3.9+）\n\n```python\n# Python 3.9+ - Use built-in types\ndef process_items(items: list[str]) -> dict[str, int]:\n    return {item: len(item) for item in items}\n\n# Python 3.8 and earlier - Use typing module\nfrom typing import List, Dict\n\ndef process_items(items: List[str]) -> Dict[str, int]:\n    return {item: len(item) for item in items}\n```\n\n### 型エイリアスとTypeVar\n\n```python\nfrom typing import TypeVar, Union\n\n# Type alias for complex types\nJSON = Union[dict[str, Any], list[Any], str, int, float, bool, None]\n\ndef parse_json(data: str) -> JSON:\n    return json.loads(data)\n\n# Generic types\nT = TypeVar('T')\n\ndef first(items: list[T]) -> T | None:\n    \"\"\"Return the first item or None if list is empty.\"\"\"\n    return items[0] if items else None\n```\n\n### プロトコルベースのダックタイピング\n\n```python\nfrom typing import Protocol\n\nclass Renderable(Protocol):\n    def render(self) -> str:\n        \"\"\"Render the object to a string.\"\"\"\n\ndef render_all(items: list[Renderable]) -> str:\n    \"\"\"Render all items that implement the Renderable protocol.\"\"\"\n    return \"\\n\".join(item.render() for item in items)\n```\n\n## エラーハンドリングパターン\n\n### 特定の例外処理\n\n```python\n# Good: Catch specific exceptions\ndef load_config(path: str) -> Config:\n    try:\n        with open(path) as f:\n            return Config.from_json(f.read())\n    except FileNotFoundError as e:\n        raise ConfigError(f\"Config file not found: {path}\") from e\n    except json.JSONDecodeError as e:\n        raise ConfigError(f\"Invalid JSON in config: {path}\") from e\n\n# Bad: Bare except\ndef load_config(path: str) -> Config:\n    try:\n        with open(path) as f:\n            return Config.from_json(f.read())\n    except:\n        return None  # Silent failure!\n```\n\n### 例外の連鎖\n\n```python\ndef process_data(data: str) -> Result:\n    try:\n        parsed = json.loads(data)\n    except json.JSONDecodeError as e:\n        # Chain exceptions to preserve the traceback\n        raise ValueError(f\"Failed to parse data: {data}\") from e\n```\n\n### カスタム例外階層\n\n```python\nclass AppError(Exception):\n    \"\"\"Base exception for all application errors.\"\"\"\n    pass\n\nclass ValidationError(AppError):\n    \"\"\"Raised when input validation fails.\"\"\"\n    pass\n\nclass NotFoundError(AppError):\n    \"\"\"Raised when a requested resource is not found.\"\"\"\n    pass\n\n# Usage\ndef get_user(user_id: str) -> User:\n    user = db.find_user(user_id)\n    if not user:\n        raise NotFoundError(f\"User not found: {user_id}\")\n    return user\n```\n\n## コンテキストマネージャ\n\n### リソース管理\n\n```python\n# Good: Using context managers\ndef process_file(path: str) -> str:\n    with open(path, 'r') as f:\n        return f.read()\n\n# Bad: Manual resource management\ndef process_file(path: str) -> str:\n    f = open(path, 'r')\n    try:\n        return f.read()\n    finally:\n        f.close()\n```\n\n### カスタムコンテキストマネージャ\n\n```python\nfrom contextlib import contextmanager\n\n@contextmanager\ndef timer(name: str):\n    \"\"\"Context manager to time a block of code.\"\"\"\n    start = time.perf_counter()\n    yield\n    elapsed = time.perf_counter() - start\n    print(f\"{name} took {elapsed:.4f} seconds\")\n\n# Usage\nwith timer(\"data processing\"):\n    process_large_dataset()\n```\n\n### コンテキストマネージャクラス\n\n```python\nclass DatabaseTransaction:\n    def __init__(self, connection):\n        self.connection = connection\n\n    def __enter__(self):\n        self.connection.begin_transaction()\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        if exc_type is None:\n            self.connection.commit()\n        else:\n            self.connection.rollback()\n        return False  # Don't suppress exceptions\n\n# Usage\nwith DatabaseTransaction(conn):\n    user = conn.create_user(user_data)\n    conn.create_profile(user.id, profile_data)\n```\n\n## 内包表記とジェネレータ\n\n### リスト内包表記\n\n```python\n# Good: List comprehension for simple transformations\nnames = [user.name for user in users if user.is_active]\n\n# Bad: Manual loop\nnames = []\nfor user in users:\n    if user.is_active:\n        names.append(user.name)\n\n# Complex comprehensions should be expanded\n# Bad: Too complex\nresult = [x * 2 for x in items if x > 0 if x % 2 == 0]\n\n# Good: Use a generator function\ndef filter_and_transform(items: Iterable[int]) -> list[int]:\n    result = []\n    for x in items:\n        if x > 0 and x % 2 == 0:\n            result.append(x * 2)\n    return result\n```\n\n### ジェネレータ式\n\n```python\n# Good: Generator for lazy evaluation\ntotal = sum(x * x for x in range(1_000_000))\n\n# Bad: Creates large intermediate list\ntotal = sum([x * x for x in range(1_000_000)])\n```\n\n### ジェネレータ関数\n\n```python\ndef read_large_file(path: str) -> Iterator[str]:\n    \"\"\"Read a large file line by line.\"\"\"\n    with open(path) as f:\n        for line in f:\n            yield line.strip()\n\n# Usage\nfor line in read_large_file(\"huge.txt\"):\n    process(line)\n```\n\n## データクラスと名前付きタプル\n\n### データクラス\n\n```python\nfrom dataclasses import dataclass, field\nfrom datetime import datetime\n\n@dataclass\nclass User:\n    \"\"\"User entity with automatic __init__, __repr__, and __eq__.\"\"\"\n    id: str\n    name: str\n    email: str\n    created_at: datetime = field(default_factory=datetime.now)\n    is_active: bool = True\n\n# Usage\nuser = User(\n    id=\"123\",\n    name=\"Alice\",\n    email=\"alice@example.com\"\n)\n```\n\n### バリデーション付きデータクラス\n\n```python\n@dataclass\nclass User:\n    email: str\n    age: int\n\n    def __post_init__(self):\n        # Validate email format\n        if \"@\" not in self.email:\n            raise ValueError(f\"Invalid email: {self.email}\")\n        # Validate age range\n        if self.age \u003C 0 or self.age > 150:\n            raise ValueError(f\"Invalid age: {self.age}\")\n```\n\n### 名前付きタプル\n\n```python\nfrom typing import NamedTuple\n\nclass Point(NamedTuple):\n    \"\"\"Immutable 2D point.\"\"\"\n    x: float\n    y: float\n\n    def distance(self, other: 'Point') -> float:\n        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5\n\n# Usage\np1 = Point(0, 0)\np2 = Point(3, 4)\nprint(p1.distance(p2))  # 5.0\n```\n\n## デコレータ\n\n### 関数デコレータ\n\n```python\nimport functools\nimport time\n\ndef timer(func: Callable) -> Callable:\n    \"\"\"Decorator to time function execution.\"\"\"\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        start = time.perf_counter()\n        result = func(*args, **kwargs)\n        elapsed = time.perf_counter() - start\n        print(f\"{func.__name__} took {elapsed:.4f}s\")\n        return result\n    return wrapper\n\n@timer\ndef slow_function():\n    time.sleep(1)\n\n# slow_function() prints: slow_function took 1.0012s\n```\n\n### パラメータ化デコレータ\n\n```python\ndef repeat(times: int):\n    \"\"\"Decorator to repeat a function multiple times.\"\"\"\n    def decorator(func: Callable) -> Callable:\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            results = []\n            for _ in range(times):\n                results.append(func(*args, **kwargs))\n            return results\n        return wrapper\n    return decorator\n\n@repeat(times=3)\ndef greet(name: str) -> str:\n    return f\"Hello, {name}!\"\n\n# greet(\"Alice\") returns [\"Hello, Alice!\", \"Hello, Alice!\", \"Hello, Alice!\"]\n```\n\n### クラスベースのデコレータ\n\n```python\nclass CountCalls:\n    \"\"\"Decorator that counts how many times a function is called.\"\"\"\n    def __init__(self, func: Callable):\n        functools.update_wrapper(self, func)\n        self.func = func\n        self.count = 0\n\n    def __call__(self, *args, **kwargs):\n        self.count += 1\n        print(f\"{self.func.__name__} has been called {self.count} times\")\n        return self.func(*args, **kwargs)\n\n@CountCalls\ndef process():\n    pass\n\n# Each call to process() prints the call count\n```\n\n## 並行処理パターン\n\n### I\u002FOバウンドタスク用のスレッド\n\n```python\nimport concurrent.futures\nimport threading\n\ndef fetch_url(url: str) -> str:\n    \"\"\"Fetch a URL (I\u002FO-bound operation).\"\"\"\n    import urllib.request\n    with urllib.request.urlopen(url) as response:\n        return response.read().decode()\n\ndef fetch_all_urls(urls: list[str]) -> dict[str, str]:\n    \"\"\"Fetch multiple URLs concurrently using threads.\"\"\"\n    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:\n        future_to_url = {executor.submit(fetch_url, url): url for url in urls}\n        results = {}\n        for future in concurrent.futures.as_completed(future_to_url):\n            url = future_to_url[future]\n            try:\n                results[url] = future.result()\n            except Exception as e:\n                results[url] = f\"Error: {e}\"\n    return results\n```\n\n### CPUバウンドタスク用のマルチプロセシング\n\n```python\ndef process_data(data: list[int]) -> int:\n    \"\"\"CPU-intensive computation.\"\"\"\n    return sum(x ** 2 for x in data)\n\ndef process_all(datasets: list[list[int]]) -> list[int]:\n    \"\"\"Process multiple datasets using multiple processes.\"\"\"\n    with concurrent.futures.ProcessPoolExecutor() as executor:\n        results = list(executor.map(process_data, datasets))\n    return results\n```\n\n### 並行I\u002FO用のAsync\u002FAwait\n\n```python\nimport asyncio\n\nasync def fetch_async(url: str) -> str:\n    \"\"\"Fetch a URL asynchronously.\"\"\"\n    import aiohttp\n    async with aiohttp.ClientSession() as session:\n        async with session.get(url) as response:\n            return await response.text()\n\nasync def fetch_all(urls: list[str]) -> dict[str, str]:\n    \"\"\"Fetch multiple URLs concurrently.\"\"\"\n    tasks = [fetch_async(url) for url in urls]\n    results = await asyncio.gather(*tasks, return_exceptions=True)\n    return dict(zip(urls, results))\n```\n\n## パッケージ構成\n\n### 標準プロジェクトレイアウト\n\n```\nmyproject\u002F\n├── src\u002F\n│   └── mypackage\u002F\n│       ├── __init__.py\n│       ├── main.py\n│       ├── api\u002F\n│       │   ├── __init__.py\n│       │   └── routes.py\n│       ├── models\u002F\n│       │   ├── __init__.py\n│       │   └── user.py\n│       └── utils\u002F\n│           ├── __init__.py\n│           └── helpers.py\n├── tests\u002F\n│   ├── __init__.py\n│   ├── conftest.py\n│   ├── test_api.py\n│   └── test_models.py\n├── pyproject.toml\n├── README.md\n└── .gitignore\n```\n\n### インポート規約\n\n```python\n# Good: Import order - stdlib, third-party, local\nimport os\nimport sys\nfrom pathlib import Path\n\nimport requests\nfrom fastapi import FastAPI\n\nfrom mypackage.models import User\nfrom mypackage.utils import format_name\n\n# Good: Use isort for automatic import sorting\n# pip install isort\n```\n\n### パッケージエクスポート用の__init__.py\n\n```python\n# mypackage\u002F__init__.py\n\"\"\"mypackage - A sample Python package.\"\"\"\n\n__version__ = \"1.0.0\"\n\n# Export main classes\u002Ffunctions at package level\nfrom mypackage.models import User, Post\nfrom mypackage.utils import format_name\n\n__all__ = [\"User\", \"Post\", \"format_name\"]\n```\n\n## メモリとパフォーマンス\n\n### メモリ効率化のための__slots__使用\n\n```python\n# Bad: Regular class uses __dict__ (more memory)\nclass Point:\n    def __init__(self, x: float, y: float):\n        self.x = x\n        self.y = y\n\n# Good: __slots__ reduces memory usage\nclass Point:\n    __slots__ = ['x', 'y']\n\n    def __init__(self, x: float, y: float):\n        self.x = x\n        self.y = y\n```\n\n### 大量データ用のジェネレータ\n\n```python\n# Bad: Returns full list in memory\ndef read_lines(path: str) -> list[str]:\n    with open(path) as f:\n        return [line.strip() for line in f]\n\n# Good: Yields lines one at a time\ndef read_lines(path: str) -> Iterator[str]:\n    with open(path) as f:\n        for line in f:\n            yield line.strip()\n```\n\n### ループ内での文字列連結を避ける\n\n```python\n# Bad: O(n²) due to string immutability\nresult = \"\"\nfor item in items:\n    result += str(item)\n\n# Good: O(n) using join\nresult = \"\".join(str(item) for item in items)\n\n# Good: Using StringIO for building\nfrom io import StringIO\n\nbuffer = StringIO()\nfor item in items:\n    buffer.write(str(item))\nresult = buffer.getvalue()\n```\n\n## Pythonツール統合\n\n### 基本コマンド\n\n```bash\n# Code formatting\nblack .\nisort .\n\n# Linting\nruff check .\npylint mypackage\u002F\n\n# Type checking\nmypy .\n\n# Testing\npytest --cov=mypackage --cov-report=html\n\n# Security scanning\nbandit -r .\n\n# Dependency management\npip-audit\nsafety check\n```\n\n### pyproject.toml設定\n\n```toml\n[project]\nname = \"mypackage\"\nversion = \"1.0.0\"\nrequires-python = \">=3.9\"\ndependencies = [\n    \"requests>=2.31.0\",\n    \"pydantic>=2.0.0\",\n]\n\n[project.optional-dependencies]\ndev = [\n    \"pytest>=7.4.0\",\n    \"pytest-cov>=4.1.0\",\n    \"black>=23.0.0\",\n    \"ruff>=0.1.0\",\n    \"mypy>=1.5.0\",\n]\n\n[tool.black]\nline-length = 88\ntarget-version = ['py39']\n\n[tool.ruff]\nline-length = 88\nselect = [\"E\", \"F\", \"I\", \"N\", \"W\"]\n\n[tool.mypy]\npython_version = \"3.9\"\nwarn_return_any = true\nwarn_unused_configs = true\ndisallow_untyped_defs = true\n\n[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\naddopts = \"--cov=mypackage --cov-report=term-missing\"\n```\n\n## クイックリファレンス：Pythonイディオム\n\n| イディオム | 説明 |\n|-------|-------------|\n| EAFP | 許可を求めるより許しを請う方が簡単 |\n| コンテキストマネージャ | リソース管理には`with`を使用 |\n| リスト内包表記 | 簡単な変換用 |\n| ジェネレータ | 遅延評価と大規模データセット用 |\n| 型ヒント | 関数シグネチャへのアノテーション |\n| データクラス | 自動生成メソッド付きデータコンテナ用 |\n| `__slots__` | メモリ最適化用 |\n| f-strings | 文字列フォーマット用（Python 3.6+） |\n| `pathlib.Path` | パス操作用（Python 3.4+） |\n| `enumerate` | ループ内のインデックス-要素ペア用 |\n\n## 避けるべきアンチパターン\n\n```python\n# Bad: Mutable default arguments\ndef append_to(item, items=[]):\n    items.append(item)\n    return items\n\n# Good: Use None and create new list\ndef append_to(item, items=None):\n    if items is None:\n        items = []\n    items.append(item)\n    return items\n\n# Bad: Checking type with type()\nif type(obj) == list:\n    process(obj)\n\n# Good: Use isinstance\nif isinstance(obj, list):\n    process(obj)\n\n# Bad: Comparing to None with ==\nif value == None:\n    process()\n\n# Good: Use is\nif value is None:\n    process()\n\n# Bad: from module import *\nfrom os.path import *\n\n# Good: Explicit imports\nfrom os.path import join, exists\n\n# Bad: Bare except\ntry:\n    risky_operation()\nexcept:\n    pass\n\n# Good: Specific exception\ntry:\n    risky_operation()\nexcept SpecificError as e:\n    logger.error(f\"Operation failed: {e}\")\n```\n\n**覚えておいてください**: Pythonコードは読みやすく、明示的で、最小の驚きの原則に従うべきです。迷ったときは、巧妙さよりも明確さを優先してください。\n",{"name":5,"description":7},"master","d6ca01da0f24a3b0e26e4a8b7b66cbd25d429f5d","skills\u002Feverything-claude-code\u002Fdocs\u002Fja-JP\u002Fskills\u002Fpython-patterns",0,"https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills","https:\u002F\u002Fgithub.com\u002FSriramGandhiS","https:\u002F\u002Fsriram.website\u002F","Curious guy who keeps tinkering until something works","2026-05-20 16:21:34",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add SriramGandhiS\u002FSkills --skill python-patterns",{"tool":39,"command":40},"bunx","bunx skills add SriramGandhiS\u002FSkills --skill python-patterns",{"tool":42,"command":43},"pnpm","pnpm dlx skills add SriramGandhiS\u002FSkills --skill python-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fskills\u002Feverything-claude-code\u002Fdocs\u002Fja-JP\u002Fskills\u002Fpython-patterns\u002FSKILL.md",true,[],[48,55,60,66,73,80],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M732609EPJWV13PVTX3GT4TM","webgpu-threejs-tsl","Comprehensive guide for developing WebGPU-enabled Three.js applications using TSL (Three.js Shading Language). Covers WebGPU renderer setup, TSL syntax and node materials, compute shaders, post-processing effects, and WGSL integration. Use this skill when working with Three.js WebGPU, TSL shaders, node materials, or GPU compute in Three.js.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fwebgpu-threejs-tsl\u002Fskills\u002Fwebgpu-threejs-tsl\u002FSKILL.md",[],[],{"skillNo":56,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M7325XM47AGWB6K6C4VXKE6B","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fwebgpu-threejs-tsl\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7325WP6DES69JKC840VMFEP","verification-loop","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fverification-loop\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7325TFQF1DZTQ6J3WGQQ1VR","tdd-workflow","Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Ftdd-workflow\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7325RGV9AY9PK92D2V8KKPW","strategic-compact","Suggests manual context compaction at logical intervals to preserve context through task phases rather than arbitrary auto-compaction.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fstrategic-compact\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7325MZC28SE86E7NMCNEFS4","security-review","Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment\u002Fsensitive features. Provides comprehensive security checklist and patterns.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fsecurity-review\u002FSKILL.md",[],[]]