[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M70GS3AS6TSX7PVF34FX7P45":3,"skill-same:01M70GS3AS6TSX7PVF34FX7P45":72},{"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":23,"publishedAt":43,"linkOnly":44,"markdownContent":45,"markdownBody":46,"frontMatter":47,"refName":50,"commitSha":51,"skillDirectory":52,"forksCount":53,"repositoryHtmlUrl":54,"repositoryHomepageUrl":6,"ownerHtmlUrl":55,"ownerBlogUrl":6,"ownerDescription":56,"updatedAt":57,"install":58,"resources":71},"01M70GS3AS6TSX7PVF34FX7P45","python-patterns",null,"Pythonic idioms, PEP 8 standards, type hints, and best practices for building robust, efficient, and maintainable Python applications. Use when writing or reviewing Python code and idiomatic structure, typing, or PEP 8 is in question.","mdnaimul22\u002Fhuman-skills","mdnaimul22","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F64520358?v=4","01M70FH95MH2H796Q01TYSFZ03","Naimul","01M70FH96798CQR4YHA13F17GA",3,"MIT","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Fpython-patterns\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42],"patterns","python patterns","python","pythonic","python code","code","when","idioms","type","best practices","use","applications","for","idiomatic","standards","structure","writing","question","typing","2026-11-10 10:12:30",false,"---\nname: python-patterns\ndescription: Pythonic idioms, PEP 8 standards, type hints, and best practices for building robust, efficient, and maintainable Python applications. Use when writing or reviewing Python code and idiomatic structure, typing, or PEP 8 is in question.\nmetadata:\n  origin: ECC\n---\n\n# Python Development Patterns\n\nIdiomatic Python patterns and best practices for building robust, efficient, and maintainable applications.\n\n## When to Activate\n\n- Writing new Python code\n- Reviewing Python code\n- Refactoring existing Python code\n- Designing Python packages\u002Fmodules\n\n## Core Principles\n\n### 1. Readability Counts\n\nPython prioritizes readability. Code should be obvious and easy to understand.\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\n# Bad: Clever but confusing\ndef get_active_users(u):\n    return [x for x in u if x.a]\n```\n\n### 2. Explicit is Better Than Implicit\n\nAvoid magic; be clear about what your code does.\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 - Easier to Ask Forgiveness Than Permission\n\nPython prefers exception handling over checking conditions.\n\n```python\n# Good: EAFP style\ndef get_value(dictionary: dict, key: str, default_value: Any = None) -> 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, default_value: Any = None) -> Any:\n    if key in dictionary:\n        return dictionary[key]\n    else:\n        return default_value\n```\n\n## Type Hints\n\n### Basic Type Annotations\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### Modern Type Hints (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### Type Aliases and 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### Protocol-Based Duck Typing\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## Error Handling Patterns\n\n### Specific Exception Handling\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### Exception Chaining\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### Custom Exception Hierarchy\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## Context Managers\n\n### Resource Management\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### Custom Context Managers\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### Context Manager Classes\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## Comprehensions and Generators\n\n### List Comprehensions\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### Generator Expressions\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### Generator Functions\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## Data Classes and Named Tuples\n\n### Data Classes\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### Data Classes with Validation\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### Named Tuples\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## Decorators\n\n### Function Decorators\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### Parameterized Decorators\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### Class-Based Decorators\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## Concurrency Patterns\n\n### Threading for I\u002FO-Bound Tasks\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### Multiprocessing for CPU-Bound Tasks\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### Async\u002FAwait for Concurrent I\u002FO\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## Package Organization\n\n### Standard Project Layout\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### Import Conventions\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 for Package Exports\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## Memory and Performance\n\n### Using __slots__ for Memory Efficiency\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### Generator for Large Data\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### Avoid String Concatenation in Loops\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 Tooling Integration\n\n### Essential Commands\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 Configuration\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## Quick Reference: Python Idioms\n\n| Idiom | Description |\n|-------|-------------|\n| EAFP | Easier to Ask Forgiveness than Permission |\n| Context managers | Use `with` for resource management |\n| List comprehensions | For simple transformations |\n| Generators | For lazy evaluation and large datasets |\n| Type hints | Annotate function signatures |\n| Dataclasses | For data containers with auto-generated methods |\n| `__slots__` | For memory optimization |\n| f-strings | For string formatting (Python 3.6+) |\n| `pathlib.Path` | For path operations (Python 3.4+) |\n| `enumerate` | For index-element pairs in loops |\n\n## Anti-Patterns to Avoid\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__Remember__: Python code should be readable, explicit, and follow the principle of least surprise. When in doubt, prioritize clarity over cleverness.\n","# Python Development Patterns\n\nIdiomatic Python patterns and best practices for building robust, efficient, and maintainable applications.\n\n## When to Activate\n\n- Writing new Python code\n- Reviewing Python code\n- Refactoring existing Python code\n- Designing Python packages\u002Fmodules\n\n## Core Principles\n\n### 1. Readability Counts\n\nPython prioritizes readability. Code should be obvious and easy to understand.\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\n# Bad: Clever but confusing\ndef get_active_users(u):\n    return [x for x in u if x.a]\n```\n\n### 2. Explicit is Better Than Implicit\n\nAvoid magic; be clear about what your code does.\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 - Easier to Ask Forgiveness Than Permission\n\nPython prefers exception handling over checking conditions.\n\n```python\n# Good: EAFP style\ndef get_value(dictionary: dict, key: str, default_value: Any = None) -> 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, default_value: Any = None) -> Any:\n    if key in dictionary:\n        return dictionary[key]\n    else:\n        return default_value\n```\n\n## Type Hints\n\n### Basic Type Annotations\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### Modern Type Hints (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### Type Aliases and 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### Protocol-Based Duck Typing\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## Error Handling Patterns\n\n### Specific Exception Handling\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### Exception Chaining\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### Custom Exception Hierarchy\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## Context Managers\n\n### Resource Management\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### Custom Context Managers\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### Context Manager Classes\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## Comprehensions and Generators\n\n### List Comprehensions\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### Generator Expressions\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### Generator Functions\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## Data Classes and Named Tuples\n\n### Data Classes\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### Data Classes with Validation\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### Named Tuples\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## Decorators\n\n### Function Decorators\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### Parameterized Decorators\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### Class-Based Decorators\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## Concurrency Patterns\n\n### Threading for I\u002FO-Bound Tasks\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### Multiprocessing for CPU-Bound Tasks\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### Async\u002FAwait for Concurrent I\u002FO\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## Package Organization\n\n### Standard Project Layout\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### Import Conventions\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 for Package Exports\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## Memory and Performance\n\n### Using __slots__ for Memory Efficiency\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### Generator for Large Data\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### Avoid String Concatenation in Loops\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 Tooling Integration\n\n### Essential Commands\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 Configuration\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## Quick Reference: Python Idioms\n\n| Idiom | Description |\n|-------|-------------|\n| EAFP | Easier to Ask Forgiveness than Permission |\n| Context managers | Use `with` for resource management |\n| List comprehensions | For simple transformations |\n| Generators | For lazy evaluation and large datasets |\n| Type hints | Annotate function signatures |\n| Dataclasses | For data containers with auto-generated methods |\n| `__slots__` | For memory optimization |\n| f-strings | For string formatting (Python 3.6+) |\n| `pathlib.Path` | For path operations (Python 3.4+) |\n| `enumerate` | For index-element pairs in loops |\n\n## Anti-Patterns to Avoid\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__Remember__: Python code should be readable, explicit, and follow the principle of least surprise. When in doubt, prioritize clarity over cleverness.\n",{"name":5,"metadata":48,"description":7},{"origin":49},"ECC","main","74715deacdc69119d739f38916f8ee4f0f979ebf","skills\u002Fstorage\u002Faffaan-m_ECC\u002Fpython-patterns",0,"https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills","https:\u002F\u002Fgithub.com\u002Fmdnaimul22","AI Agents Workflows Automation | Specializing in Python, FastAPI, MCP Agents & Custom ERP.","2026-11-11 06:54:12",{"source":8,"skillName":5,"commands":59,"prompt":69,"zipAvailable":70},[60,63,66],{"tool":61,"command":62},"npx","npx skills add mdnaimul22\u002Fhuman-skills --skill python-patterns",{"tool":64,"command":65},"bunx","bunx skills add mdnaimul22\u002Fhuman-skills --skill python-patterns",{"tool":67,"command":68},"pnpm","pnpm dlx skills add mdnaimul22\u002Fhuman-skills --skill python-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Fpython-patterns\u002FSKILL.md",true,[],[73,81,108,126,145,160],{"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":80},"01M72JT3YP1SQHD0MANGDXQ4RT","higgsfield-websites","Build, edit, and deploy full-stack websites, apps and games via the Higgsfield CLI (`higgsfield website …`). Each is a React 19 + TanStack Start SSR app in one Cloudflare Worker (D1\u002FR2\u002FKV\u002FDO\u002FContainers). THREE product types, picked via `--type` on create: `website` (standalone, no Higgsfield integration — references\u002Fwebsite-flow.md), `app` (Sign in with Higgsfield + fnf SDK, Quanta — references\u002Fapp-flow.md), `game` (realtime multiplayer rooms — references\u002Fgame-flow.md). Routes to the right flow; each carries its own rules and deploy\u002Fpublish gates.\nUse when: \"build me a website\", \"make a landing page\", \"create a web app\", \"build a SaaS dashboard \u002F portfolio\", \"make me a game\", \"deploy this site\", \"publish\". Also owns GAME ART: \"make a spritesheet\", \"tileable texture\", \"animate a 3D character\", game music\u002FSFX — see the game-* references.\nNOT for: single image\u002Fvideo\u002Faudio generation (higgsfield-generate), product photos (higgsfield-product-photoshoot), marketplace cards (higgsfield-marketplace-cards).","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fhiggsfield-ai_skills\u002Fhiggsfield-websites\u002FSKILL.md",[],[],"2026-11-10 22:39:42",{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":101,"publishedAt":43},"01M70JPK8HAXXA85P7Q8NKZZYG","writing-skills","Use when creating new skills, editing existing skills, or verifying skills work before deployment","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fobra_superpowers\u002Fwriting-skills\u002FSKILL.md",[87,92,95,98],{"categoryNo":88,"categoryName":89,"taxonomyType":90,"taxonomyTypeDesc":91},"01JBSEEDCAT000000000000018","写作与文案","SCENARIO","使用场景",{"categoryNo":93,"categoryName":94,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000036","内容创作者",{"categoryNo":96,"categoryName":97,"taxonomyType":90,"taxonomyTypeDesc":91},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":99,"categoryName":100,"taxonomyType":90,"taxonomyTypeDesc":91},"01JBSEEDCAT000000000000008","测试与质量",[40,102,103,104,34,105,106,30,107],"writing skills","editing","deployment","Existing","new","work",{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":117,"publishedAt":43},"01M70JP4PHBH1CQVVDWZ94W159","writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fobra_superpowers\u002Fwriting-plans\u002FSKILL.md",[114,115,116],{"categoryNo":88,"categoryName":89,"taxonomyType":90,"taxonomyTypeDesc":91},{"categoryNo":93,"categoryName":94,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},[40,118,119,120,30,29,36,34,121,122,123,124,125],"writing plans","plans","you","requirements","task","multi","spec","multi-step task",{"skillNo":127,"name":128,"nameZh":6,"description":129,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":130,"categories":131,"keywords":132,"publishedAt":43},"01M70JNTYVGXFZT8PASZ844TH8","verification-before-completion","Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fobra_superpowers\u002Fverification-before-completion\u002FSKILL.md",[],[133,134,135,136,137,138,34,139,140,141,30,142,107,143,144],"verification","verification before completion","complete","about","output","assertions","prs","evidence","claim","claims","commands","running",{"skillNo":146,"name":147,"nameZh":6,"description":148,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":149,"categories":150,"keywords":152,"publishedAt":43},"01M70JNGVSQDESWN0Q5BPJ875V","using-superpowers","Use when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fobra_superpowers\u002Fusing-superpowers\u002FSKILL.md",[151],{"categoryNo":96,"categoryName":97,"taxonomyType":90,"taxonomyTypeDesc":91},[153,154,155,156,34,30,157,158,159],"using superpowers","superpowers","conversation","how to","how","find","questions",{"skillNo":161,"name":162,"nameZh":6,"description":163,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":164,"categories":165,"keywords":166,"publishedAt":43},"01M70JN57CE588NPYPYTWH1DWG","using-git-worktrees","Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fobra_superpowers\u002Fusing-git-worktrees\u002FSKILL.md",[],[167,168,169,170,171,172,30,107,173,174,175,176,177,178,179,119,34,180,181],"using git worktrees","Using git","git","worktrees","git worktrees","implementation","git worktree","worktree","native","Tools","isolation","fallback","feature","via","workspace"]