[{"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 21:16:57",{"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,89,96,103,110],{"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},"01M767791C1KRP2ZRW2Z73VZ5Q","system-lifecycle-designer","Universal architectural methodology for designing granular, atomic, and sub-atomic lifecycles and end-to-end workflows for single functionality integrations across any domain (daemons, batch jobs, request transactions, resource pools). Provides patterns for deterministic identity, pre-commit validation, differential reconciliation, sticky leasing, state machines, transactional persistence, and closed-loop feedback.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fmy_skills\u002Fsystem-lifecycle-designer\u002FSKILL.md",[],[],"2026-11-12 13:55:43",{"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":87,"publishedAt":88},"01M748ABPN5F1FANHH6HKZQMXT","style-sampling","Make a new episode in a proven video style - Collage Explainer, Finance Explainer, Animated Science Explainer, 3D Brand Explainer, 3D True Crime - on the person's topic. Use for \"an episode of\", \"in the style of\", \"sample this style\", 「用这个风格做一集」. One video to copy is reverse-any-video.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fheygen-com_hyperframes\u002Fstyle-sampling\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":88},"01M748A59V04PKW4HA0XQ81FGP","reverse-any-video","Rebuild any video file as an editable HyperFrames project - motion graphics, talking heads, live action or AI-generated footage - checked against the original frame by frame. Use to reverse, recreate, remake, replicate or copy a video, or 「复刻这个视频」「照着这个视频做一个」.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fheygen-com_hyperframes\u002Freverse-any-video\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":88},"01M7487T50P55CSXMWXZ0G9KRG","typescript-patterns","TypeScript patterns for strict, type-safe, maintainable code in modern TypeScript and JavaScript applications. Covers strict compiler configuration, type design, narrowing, discriminated unions, generics, async and error handling, module boundaries, dependency hygiene, and type-level testing. Use when writing or reviewing TypeScript or JavaScript code.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Ftypescript-patterns\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":88},"01M7487ERZRGPC5NJ75077Y238","test-collaboration","Inventory and govern a project's test assets. Connect requirements, business rules, risks, bugs, and cross-boundary contracts to stable TEST-IDs and executable evidence in the repository's existing test registry or TESTS.md. Use for test inventory, test gap analysis, unit\u002Fintegration\u002Fcontract\u002FE2E\u002Fsmoke classification, bug-to-test regression protection, consumer\u002Fprovider contract testing, test-necessity review, and pre-delivery evidence review.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Ftest-collaboration\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":88},"01M748721J3GKR2WS6K0QWFC35","story-lifecycle","Manage a file-based epic → story → sprint development loop without requiring an external project management tool. Creates and tracks epics, breaks them into user stories, assigns them to sprints, and drives implementation story by story. Use when starting a new feature initiative or when the team has no Jira\u002FLinear\u002FTaiga but needs structured delivery tracking.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Fstory-lifecycle\u002FSKILL.md",[],[]]