[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6CD2VP7Z8WA06J395VBBB04":3,"skill-same:01M6CD2VP7Z8WA06J395VBBB04":80},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":48,"linkOnly":49,"markdownContent":50,"markdownBody":51,"frontMatter":52,"refName":54,"commitSha":55,"skillDirectory":56,"forksCount":57,"repositoryHtmlUrl":58,"repositoryHomepageUrl":17,"ownerHtmlUrl":59,"ownerBlogUrl":17,"ownerDescription":17,"updatedAt":60,"install":61,"resources":73},"01M6CD2VP7Z8WA06J395VBBB04","python-resource-management","Python 资源管理与清理","Python resource management with context managers, cleanup patterns, and streaming. Use when managing connections, file handles, implementing cleanup logic, or building streaming responses with accumulated state.","Python 资源管理，涵盖上下文管理器、清理模式和流式处理。适用于管理连接、文件句柄、实现清理逻辑，或构建带累积状态的流式响应。","cercova-studios\u002F10x-swe","cercova-studios","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F217108198?v=4","01M6CCYGHXTH80N3BXRW6KESTE","Cercova Studios","01M6CCYGPADH5MJDR0VNNR775C",1,"MIT",null,"https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Fpython-resource-management\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQ6TQZN6R52WBJ9H8NRMQM","软件开发工程师","PROFESSION","适用职业",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8CEEYW9437JC839V6V453Q5","Python 开发","SCENARIO","使用场景",[31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47],"management","python resource management","python","resource management","patterns","logic","with","managers","when","connections","implementing","streaming","context","file","use","cleanup","state","2026-11-10 10:12:30",false,"---\nname: python-resource-management\ndescription: Python resource management with context managers, cleanup patterns, and streaming. Use when managing connections, file handles, implementing cleanup logic, or building streaming responses with accumulated state.\ndisable-model-invocation: true\n---\n\n# Python Resource Management\n\nManage resources deterministically using context managers. Resources like database connections, file handles, and network sockets should be released reliably, even when exceptions occur.\n\n## When to Use This Skill\n\n- Managing database connections and connection pools\n- Working with file handles and I\u002FO\n- Implementing custom context managers\n- Building streaming responses with state\n- Handling nested resource cleanup\n- Creating async context managers\n\n## Core Concepts\n\n### 1. Context Managers\n\nThe `with` statement ensures resources are released automatically, even on exceptions.\n\n### 2. Protocol Methods\n\n`__enter__`\u002F`__exit__` for sync, `__aenter__`\u002F`__aexit__` for async resource management.\n\n### 3. Unconditional Cleanup\n\n`__exit__` always runs, regardless of whether an exception occurred.\n\n### 4. Exception Handling\n\nReturn `True` from `__exit__` to suppress exceptions, `False` to propagate them.\n\n## Quick Start\n\n```python\nfrom contextlib import contextmanager\n\n@contextmanager\ndef managed_resource():\n    resource = acquire_resource()\n    try:\n        yield resource\n    finally:\n        resource.cleanup()\n\nwith managed_resource() as r:\n    r.do_work()\n```\n\n## Fundamental Patterns\n\n### Pattern 1: Class-Based Context Manager\n\nImplement the context manager protocol for complex resources.\n\n```python\nclass DatabaseConnection:\n    \"\"\"Database connection with automatic cleanup.\"\"\"\n\n    def __init__(self, dsn: str) -> None:\n        self._dsn = dsn\n        self._conn: Connection | None = None\n\n    def connect(self) -> None:\n        \"\"\"Establish database connection.\"\"\"\n        self._conn = psycopg.connect(self._dsn)\n\n    def close(self) -> None:\n        \"\"\"Close connection if open.\"\"\"\n        if self._conn is not None:\n            self._conn.close()\n            self._conn = None\n\n    def __enter__(self) -> \"DatabaseConnection\":\n        \"\"\"Enter context: connect and return self.\"\"\"\n        self.connect()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        \"\"\"Exit context: always close connection.\"\"\"\n        self.close()\n\n# Usage with context manager (preferred)\nwith DatabaseConnection(dsn) as db:\n    result = db.execute(query)\n\n# Manual management when needed\ndb = DatabaseConnection(dsn)\ndb.connect()\ntry:\n    result = db.execute(query)\nfinally:\n    db.close()\n```\n\n### Pattern 2: Async Context Manager\n\nFor async resources, implement the async protocol.\n\n```python\nclass AsyncDatabasePool:\n    \"\"\"Async database connection pool.\"\"\"\n\n    def __init__(self, dsn: str, min_size: int = 1, max_size: int = 10) -> None:\n        self._dsn = dsn\n        self._min_size = min_size\n        self._max_size = max_size\n        self._pool: asyncpg.Pool | None = None\n\n    async def __aenter__(self) -> \"AsyncDatabasePool\":\n        \"\"\"Create connection pool.\"\"\"\n        self._pool = await asyncpg.create_pool(\n            self._dsn,\n            min_size=self._min_size,\n            max_size=self._max_size,\n        )\n        return self\n\n    async def __aexit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        \"\"\"Close all connections in pool.\"\"\"\n        if self._pool is not None:\n            await self._pool.close()\n\n    async def execute(self, query: str, *args) -> list[dict]:\n        \"\"\"Execute query using pooled connection.\"\"\"\n        async with self._pool.acquire() as conn:\n            return await conn.fetch(query, *args)\n\n# Usage\nasync with AsyncDatabasePool(dsn) as pool:\n    users = await pool.execute(\"SELECT * FROM users WHERE active = $1\", True)\n```\n\n### Pattern 3: Using @contextmanager Decorator\n\nSimplify context managers with the decorator for straightforward cases.\n\n```python\nfrom contextlib import contextmanager, asynccontextmanager\nimport time\nimport structlog\n\nlogger = structlog.get_logger()\n\n@contextmanager\ndef timed_block(name: str):\n    \"\"\"Time a block of code.\"\"\"\n    start = time.perf_counter()\n    try:\n        yield\n    finally:\n        elapsed = time.perf_counter() - start\n        logger.info(f\"{name} completed\", duration_seconds=round(elapsed, 3))\n\n# Usage\nwith timed_block(\"data_processing\"):\n    process_large_dataset()\n\n@asynccontextmanager\nasync def database_transaction(conn: AsyncConnection):\n    \"\"\"Manage database transaction.\"\"\"\n    await conn.execute(\"BEGIN\")\n    try:\n        yield conn\n        await conn.execute(\"COMMIT\")\n    except Exception:\n        await conn.execute(\"ROLLBACK\")\n        raise\n\n# Usage\nasync with database_transaction(conn) as tx:\n    await tx.execute(\"INSERT INTO users ...\")\n    await tx.execute(\"INSERT INTO audit_log ...\")\n```\n\n### Pattern 4: Unconditional Resource Release\n\nAlways clean up resources in `__exit__`, regardless of exceptions.\n\n```python\nclass FileProcessor:\n    \"\"\"Process file with guaranteed cleanup.\"\"\"\n\n    def __init__(self, path: str) -> None:\n        self._path = path\n        self._file: IO | None = None\n        self._temp_files: list[Path] = []\n\n    def __enter__(self) -> \"FileProcessor\":\n        self._file = open(self._path, \"r\")\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        \"\"\"Clean up all resources unconditionally.\"\"\"\n        # Close main file\n        if self._file is not None:\n            self._file.close()\n\n        # Clean up any temporary files\n        for temp_file in self._temp_files:\n            try:\n                temp_file.unlink()\n            except OSError:\n                pass  # Best effort cleanup\n\n        # Return None\u002FFalse to propagate any exception\n```\n\n## Advanced Patterns\n\n### Pattern 5: Selective Exception Suppression\n\nOnly suppress specific, documented exceptions.\n\n```python\nclass StreamWriter:\n    \"\"\"Writer that handles broken pipe gracefully.\"\"\"\n\n    def __init__(self, stream) -> None:\n        self._stream = stream\n\n    def __enter__(self) -> \"StreamWriter\":\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        \"\"\"Clean up, suppressing BrokenPipeError on shutdown.\"\"\"\n        self._stream.close()\n\n        # Suppress BrokenPipeError (client disconnected)\n        # This is expected behavior, not an error\n        if exc_type is BrokenPipeError:\n            return True  # Exception suppressed\n\n        return False  # Propagate all other exceptions\n```\n\n### Pattern 6: Streaming with Accumulated State\n\nMaintain both incremental chunks and accumulated state during streaming.\n\n```python\nfrom collections.abc import Generator\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass StreamingResult:\n    \"\"\"Accumulated streaming result.\"\"\"\n\n    chunks: list[str] = field(default_factory=list)\n    _finalized: bool = False\n\n    @property\n    def content(self) -> str:\n        \"\"\"Get accumulated content.\"\"\"\n        return \"\".join(self.chunks)\n\n    def add_chunk(self, chunk: str) -> None:\n        \"\"\"Add chunk to accumulator.\"\"\"\n        if self._finalized:\n            raise RuntimeError(\"Cannot add to finalized result\")\n        self.chunks.append(chunk)\n\n    def finalize(self) -> str:\n        \"\"\"Mark stream complete and return content.\"\"\"\n        self._finalized = True\n        return self.content\n\ndef stream_with_accumulation(\n    response: StreamingResponse,\n) -> Generator[tuple[str, str], None, str]:\n    \"\"\"Stream response while accumulating content.\n\n    Yields:\n        Tuple of (accumulated_content, new_chunk) for each chunk.\n\n    Returns:\n        Final accumulated content.\n    \"\"\"\n    result = StreamingResult()\n\n    for chunk in response.iter_content():\n        result.add_chunk(chunk)\n        yield result.content, chunk\n\n    return result.finalize()\n```\n\n### Pattern 7: Efficient String Accumulation\n\nAvoid O(n²) string concatenation when accumulating.\n\n```python\ndef accumulate_stream(stream) -> str:\n    \"\"\"Efficiently accumulate stream content.\"\"\"\n    # BAD: O(n²) due to string immutability\n    # content = \"\"\n    # for chunk in stream:\n    #     content += chunk  # Creates new string each time\n\n    # GOOD: O(n) with list and join\n    chunks: list[str] = []\n    for chunk in stream:\n        chunks.append(chunk)\n    return \"\".join(chunks)  # Single allocation\n```\n\n### Pattern 8: Tracking Stream Metrics\n\nMeasure time-to-first-byte and total streaming time.\n\n```python\nimport time\nfrom collections.abc import Generator\n\ndef stream_with_metrics(\n    response: StreamingResponse,\n) -> Generator[str, None, dict]:\n    \"\"\"Stream response while collecting metrics.\n\n    Yields:\n        Content chunks.\n\n    Returns:\n        Metrics dictionary.\n    \"\"\"\n    start = time.perf_counter()\n    first_chunk_time: float | None = None\n    chunk_count = 0\n    total_bytes = 0\n\n    for chunk in response.iter_content():\n        if first_chunk_time is None:\n            first_chunk_time = time.perf_counter() - start\n\n        chunk_count += 1\n        total_bytes += len(chunk.encode())\n        yield chunk\n\n    total_time = time.perf_counter() - start\n\n    return {\n        \"time_to_first_byte_ms\": round((first_chunk_time or 0) * 1000, 2),\n        \"total_time_ms\": round(total_time * 1000, 2),\n        \"chunk_count\": chunk_count,\n        \"total_bytes\": total_bytes,\n    }\n```\n\n### Pattern 9: Managing Multiple Resources with ExitStack\n\nHandle a dynamic number of resources cleanly.\n\n```python\nfrom contextlib import ExitStack, AsyncExitStack\nfrom pathlib import Path\n\ndef process_files(paths: list[Path]) -> list[str]:\n    \"\"\"Process multiple files with automatic cleanup.\"\"\"\n    results = []\n\n    with ExitStack() as stack:\n        # Open all files - they'll all be closed when block exits\n        files = [stack.enter_context(open(p)) for p in paths]\n\n        for f in files:\n            results.append(f.read())\n\n    return results\n\nasync def process_connections(hosts: list[str]) -> list[dict]:\n    \"\"\"Process multiple async connections.\"\"\"\n    results = []\n\n    async with AsyncExitStack() as stack:\n        connections = [\n            await stack.enter_async_context(connect_to_host(host))\n            for host in hosts\n        ]\n\n        for conn in connections:\n            results.append(await conn.fetch_data())\n\n    return results\n```\n\n## Best Practices Summary\n\n1. **Always use context managers** - For any resource that needs cleanup\n2. **Clean up unconditionally** - `__exit__` runs even on exception\n3. **Don't suppress unexpectedly** - Return `False` unless suppression is intentional\n4. **Use @contextmanager** - For simple resource patterns\n5. **Implement both protocols** - Support `with` and manual management\n6. **Use ExitStack** - For dynamic numbers of resources\n7. **Accumulate efficiently** - List + join, not string concatenation\n8. **Track metrics** - Time-to-first-byte matters for streaming\n9. **Document behavior** - Especially exception suppression\n10. **Test cleanup paths** - Verify resources are released on errors\n","# Python Resource Management\n\nManage resources deterministically using context managers. Resources like database connections, file handles, and network sockets should be released reliably, even when exceptions occur.\n\n## When to Use This Skill\n\n- Managing database connections and connection pools\n- Working with file handles and I\u002FO\n- Implementing custom context managers\n- Building streaming responses with state\n- Handling nested resource cleanup\n- Creating async context managers\n\n## Core Concepts\n\n### 1. Context Managers\n\nThe `with` statement ensures resources are released automatically, even on exceptions.\n\n### 2. Protocol Methods\n\n`__enter__`\u002F`__exit__` for sync, `__aenter__`\u002F`__aexit__` for async resource management.\n\n### 3. Unconditional Cleanup\n\n`__exit__` always runs, regardless of whether an exception occurred.\n\n### 4. Exception Handling\n\nReturn `True` from `__exit__` to suppress exceptions, `False` to propagate them.\n\n## Quick Start\n\n```python\nfrom contextlib import contextmanager\n\n@contextmanager\ndef managed_resource():\n    resource = acquire_resource()\n    try:\n        yield resource\n    finally:\n        resource.cleanup()\n\nwith managed_resource() as r:\n    r.do_work()\n```\n\n## Fundamental Patterns\n\n### Pattern 1: Class-Based Context Manager\n\nImplement the context manager protocol for complex resources.\n\n```python\nclass DatabaseConnection:\n    \"\"\"Database connection with automatic cleanup.\"\"\"\n\n    def __init__(self, dsn: str) -> None:\n        self._dsn = dsn\n        self._conn: Connection | None = None\n\n    def connect(self) -> None:\n        \"\"\"Establish database connection.\"\"\"\n        self._conn = psycopg.connect(self._dsn)\n\n    def close(self) -> None:\n        \"\"\"Close connection if open.\"\"\"\n        if self._conn is not None:\n            self._conn.close()\n            self._conn = None\n\n    def __enter__(self) -> \"DatabaseConnection\":\n        \"\"\"Enter context: connect and return self.\"\"\"\n        self.connect()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        \"\"\"Exit context: always close connection.\"\"\"\n        self.close()\n\n# Usage with context manager (preferred)\nwith DatabaseConnection(dsn) as db:\n    result = db.execute(query)\n\n# Manual management when needed\ndb = DatabaseConnection(dsn)\ndb.connect()\ntry:\n    result = db.execute(query)\nfinally:\n    db.close()\n```\n\n### Pattern 2: Async Context Manager\n\nFor async resources, implement the async protocol.\n\n```python\nclass AsyncDatabasePool:\n    \"\"\"Async database connection pool.\"\"\"\n\n    def __init__(self, dsn: str, min_size: int = 1, max_size: int = 10) -> None:\n        self._dsn = dsn\n        self._min_size = min_size\n        self._max_size = max_size\n        self._pool: asyncpg.Pool | None = None\n\n    async def __aenter__(self) -> \"AsyncDatabasePool\":\n        \"\"\"Create connection pool.\"\"\"\n        self._pool = await asyncpg.create_pool(\n            self._dsn,\n            min_size=self._min_size,\n            max_size=self._max_size,\n        )\n        return self\n\n    async def __aexit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        \"\"\"Close all connections in pool.\"\"\"\n        if self._pool is not None:\n            await self._pool.close()\n\n    async def execute(self, query: str, *args) -> list[dict]:\n        \"\"\"Execute query using pooled connection.\"\"\"\n        async with self._pool.acquire() as conn:\n            return await conn.fetch(query, *args)\n\n# Usage\nasync with AsyncDatabasePool(dsn) as pool:\n    users = await pool.execute(\"SELECT * FROM users WHERE active = $1\", True)\n```\n\n### Pattern 3: Using @contextmanager Decorator\n\nSimplify context managers with the decorator for straightforward cases.\n\n```python\nfrom contextlib import contextmanager, asynccontextmanager\nimport time\nimport structlog\n\nlogger = structlog.get_logger()\n\n@contextmanager\ndef timed_block(name: str):\n    \"\"\"Time a block of code.\"\"\"\n    start = time.perf_counter()\n    try:\n        yield\n    finally:\n        elapsed = time.perf_counter() - start\n        logger.info(f\"{name} completed\", duration_seconds=round(elapsed, 3))\n\n# Usage\nwith timed_block(\"data_processing\"):\n    process_large_dataset()\n\n@asynccontextmanager\nasync def database_transaction(conn: AsyncConnection):\n    \"\"\"Manage database transaction.\"\"\"\n    await conn.execute(\"BEGIN\")\n    try:\n        yield conn\n        await conn.execute(\"COMMIT\")\n    except Exception:\n        await conn.execute(\"ROLLBACK\")\n        raise\n\n# Usage\nasync with database_transaction(conn) as tx:\n    await tx.execute(\"INSERT INTO users ...\")\n    await tx.execute(\"INSERT INTO audit_log ...\")\n```\n\n### Pattern 4: Unconditional Resource Release\n\nAlways clean up resources in `__exit__`, regardless of exceptions.\n\n```python\nclass FileProcessor:\n    \"\"\"Process file with guaranteed cleanup.\"\"\"\n\n    def __init__(self, path: str) -> None:\n        self._path = path\n        self._file: IO | None = None\n        self._temp_files: list[Path] = []\n\n    def __enter__(self) -> \"FileProcessor\":\n        self._file = open(self._path, \"r\")\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        \"\"\"Clean up all resources unconditionally.\"\"\"\n        # Close main file\n        if self._file is not None:\n            self._file.close()\n\n        # Clean up any temporary files\n        for temp_file in self._temp_files:\n            try:\n                temp_file.unlink()\n            except OSError:\n                pass  # Best effort cleanup\n\n        # Return None\u002FFalse to propagate any exception\n```\n\n## Advanced Patterns\n\n### Pattern 5: Selective Exception Suppression\n\nOnly suppress specific, documented exceptions.\n\n```python\nclass StreamWriter:\n    \"\"\"Writer that handles broken pipe gracefully.\"\"\"\n\n    def __init__(self, stream) -> None:\n        self._stream = stream\n\n    def __enter__(self) -> \"StreamWriter\":\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        \"\"\"Clean up, suppressing BrokenPipeError on shutdown.\"\"\"\n        self._stream.close()\n\n        # Suppress BrokenPipeError (client disconnected)\n        # This is expected behavior, not an error\n        if exc_type is BrokenPipeError:\n            return True  # Exception suppressed\n\n        return False  # Propagate all other exceptions\n```\n\n### Pattern 6: Streaming with Accumulated State\n\nMaintain both incremental chunks and accumulated state during streaming.\n\n```python\nfrom collections.abc import Generator\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass StreamingResult:\n    \"\"\"Accumulated streaming result.\"\"\"\n\n    chunks: list[str] = field(default_factory=list)\n    _finalized: bool = False\n\n    @property\n    def content(self) -> str:\n        \"\"\"Get accumulated content.\"\"\"\n        return \"\".join(self.chunks)\n\n    def add_chunk(self, chunk: str) -> None:\n        \"\"\"Add chunk to accumulator.\"\"\"\n        if self._finalized:\n            raise RuntimeError(\"Cannot add to finalized result\")\n        self.chunks.append(chunk)\n\n    def finalize(self) -> str:\n        \"\"\"Mark stream complete and return content.\"\"\"\n        self._finalized = True\n        return self.content\n\ndef stream_with_accumulation(\n    response: StreamingResponse,\n) -> Generator[tuple[str, str], None, str]:\n    \"\"\"Stream response while accumulating content.\n\n    Yields:\n        Tuple of (accumulated_content, new_chunk) for each chunk.\n\n    Returns:\n        Final accumulated content.\n    \"\"\"\n    result = StreamingResult()\n\n    for chunk in response.iter_content():\n        result.add_chunk(chunk)\n        yield result.content, chunk\n\n    return result.finalize()\n```\n\n### Pattern 7: Efficient String Accumulation\n\nAvoid O(n²) string concatenation when accumulating.\n\n```python\ndef accumulate_stream(stream) -> str:\n    \"\"\"Efficiently accumulate stream content.\"\"\"\n    # BAD: O(n²) due to string immutability\n    # content = \"\"\n    # for chunk in stream:\n    #     content += chunk  # Creates new string each time\n\n    # GOOD: O(n) with list and join\n    chunks: list[str] = []\n    for chunk in stream:\n        chunks.append(chunk)\n    return \"\".join(chunks)  # Single allocation\n```\n\n### Pattern 8: Tracking Stream Metrics\n\nMeasure time-to-first-byte and total streaming time.\n\n```python\nimport time\nfrom collections.abc import Generator\n\ndef stream_with_metrics(\n    response: StreamingResponse,\n) -> Generator[str, None, dict]:\n    \"\"\"Stream response while collecting metrics.\n\n    Yields:\n        Content chunks.\n\n    Returns:\n        Metrics dictionary.\n    \"\"\"\n    start = time.perf_counter()\n    first_chunk_time: float | None = None\n    chunk_count = 0\n    total_bytes = 0\n\n    for chunk in response.iter_content():\n        if first_chunk_time is None:\n            first_chunk_time = time.perf_counter() - start\n\n        chunk_count += 1\n        total_bytes += len(chunk.encode())\n        yield chunk\n\n    total_time = time.perf_counter() - start\n\n    return {\n        \"time_to_first_byte_ms\": round((first_chunk_time or 0) * 1000, 2),\n        \"total_time_ms\": round(total_time * 1000, 2),\n        \"chunk_count\": chunk_count,\n        \"total_bytes\": total_bytes,\n    }\n```\n\n### Pattern 9: Managing Multiple Resources with ExitStack\n\nHandle a dynamic number of resources cleanly.\n\n```python\nfrom contextlib import ExitStack, AsyncExitStack\nfrom pathlib import Path\n\ndef process_files(paths: list[Path]) -> list[str]:\n    \"\"\"Process multiple files with automatic cleanup.\"\"\"\n    results = []\n\n    with ExitStack() as stack:\n        # Open all files - they'll all be closed when block exits\n        files = [stack.enter_context(open(p)) for p in paths]\n\n        for f in files:\n            results.append(f.read())\n\n    return results\n\nasync def process_connections(hosts: list[str]) -> list[dict]:\n    \"\"\"Process multiple async connections.\"\"\"\n    results = []\n\n    async with AsyncExitStack() as stack:\n        connections = [\n            await stack.enter_async_context(connect_to_host(host))\n            for host in hosts\n        ]\n\n        for conn in connections:\n            results.append(await conn.fetch_data())\n\n    return results\n```\n\n## Best Practices Summary\n\n1. **Always use context managers** - For any resource that needs cleanup\n2. **Clean up unconditionally** - `__exit__` runs even on exception\n3. **Don't suppress unexpectedly** - Return `False` unless suppression is intentional\n4. **Use @contextmanager** - For simple resource patterns\n5. **Implement both protocols** - Support `with` and manual management\n6. **Use ExitStack** - For dynamic numbers of resources\n7. **Accumulate efficiently** - List + join, not string concatenation\n8. **Track metrics** - Time-to-first-byte matters for streaming\n9. **Document behavior** - Especially exception suppression\n10. **Test cleanup paths** - Verify resources are released on errors\n",{"name":5,"description":7,"disable-model-invocation":53},true,"main","224d7699a283a75bd3f75d4d8b03b15aca0ae309","plugins\u002F10x-swe\u002Fskills\u002Fpython-resource-management",0,"https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe","https:\u002F\u002Fgithub.com\u002Fcercova-studios","2026-11-12 07:39:44",{"source":9,"skillName":5,"commands":62,"prompt":72,"zipAvailable":53},[63,66,69],{"tool":64,"command":65},"npx","npx skills add cercova-studios\u002F10x-swe --skill python-resource-management",{"tool":67,"command":68},"bunx","bunx skills add cercova-studios\u002F10x-swe --skill python-resource-management",{"tool":70,"command":71},"pnpm","pnpm dlx skills add cercova-studios\u002F10x-swe --skill python-resource-management","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Fpython-resource-management\u002FSKILL.md",[74],{"path":75,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":78,"sourceHtmlUrl":79},"agents\u002Fopenai.yaml","REFERENCE","参考文档",43,"https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Fpython-resource-management\u002Fagents\u002Fopenai.yaml",[81,89,124,149,177,201],{"skillNo":82,"name":83,"nameZh":17,"description":84,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":88},"01M78M2BEZ8C1STWW1Q0AQKKAD","10x-mode","Route a hard engineering task to one existing workflow. Use for a bug fix, refactor, feature, architecture or investigation, parallel work, or finishing a branch or pull request, including when the user asks for 10x-mode.","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002F10x-mode\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":90,"name":91,"nameZh":17,"description":92,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":93,"licenseFileUrl":94,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":48},"01M6CD3T6EQ9N5KPNXCM6ABHVA","turnstile-spin","Set up Cloudflare Turnstile end-to-end in a project. Scan the codebase, create the widget via the Cloudflare API, embed it where user requests need bot verification (form submissions, SPA actions, API endpoints, download links, comment or vote submissions, etc.), wire canonical server-side siteverify in the customer's existing backend, validate, and persist the skill. Load this when a user asks to add Turnstile, set up CAPTCHA, protect a form or endpoint from bots, or fix a Turnstile integration. Uses Cloudflare's documented Turnstile contract.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Fturnstile-spin\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Fturnstile-spin\u002FSKILL.md",[],[98,99,39,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123],"turnstile spin","end","SWE","nextjs","SET","actions","verification","spa","bots","app","integration","sveltekit","backend","customer","endpoints","plugin","project","server","astro","create","permissions","api","bot","cloudflare","fix","up",{"skillNo":125,"name":126,"nameZh":17,"description":127,"descriptionZh":17,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":93,"licenseFileUrl":128,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":48},"01M6CD0BJYRNV610HYYPX933RE","frontend-design","Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Ffrontend-design\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002F10x-swe\u002Fskills\u002Ffrontend-design\u002FSKILL.md",[],[132,133,134,135,136,137,37,39,138,139,140,141,142,45,143,144,145,146,147,148,117],"frontend","frontend design","design","components","build","high","pages","aesthetics","generic","user","code","Production","web components","creative","applications","quality","web",{"skillNo":150,"name":151,"nameZh":152,"description":153,"descriptionZh":154,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":155,"categories":156,"keywords":163,"publishedAt":48},"01M6CD4QX8C4DST98AY21HEYCM","source-insights","来源证据与洞察管理","Prepare inspected source evidence, preserve exact citations, and publish reviewed insights into an explicit local library.","整理已检查的来源证据，保留精确引用，并将审阅后的洞察发布到明确的本地库中。","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002Fknowledge\u002Fskills\u002Fsource-insights\u002FSKILL.md",[157,160],{"categoryNo":158,"categoryName":159,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQ6TRAEZFJ43R95HPEBJYG","知识工作者",{"categoryNo":161,"categoryName":162,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BRFRAYBCBW9WKDY9TCSHY3","知识管理与沉淀",[164,165,166,167,168,169,170,171,172,173,174,175,176],"source insights","insights","source","preserve","local","global","session","prepare","workflows","library","evidence","Citations","publish",{"skillNo":178,"name":179,"nameZh":180,"description":181,"descriptionZh":182,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":183,"categories":184,"keywords":191,"publishedAt":48},"01M6CD4N1HVNC1EXPEBZT7YS31","skill-graph","技能图谱发现","Discover skills and workflows through independent lexical search, relationship paths and a terminal graph.","通过独立的词汇搜索、关系路径和终端图谱来发现技能与工作流。","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002Fknowledge\u002Fskills\u002Fskill-graph\u002FSKILL.md",[185,188],{"categoryNo":186,"categoryName":187,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BRN0CV1NMDZ5TEJX1GVM29","插件与技能管理",{"categoryNo":189,"categoryName":190,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BRZZF9D7PVFN5MXSPWWD61","AI 工程师",[192,193,113,194,172,100,195,196,197,169,198,199,200],"graph","skill graph","relationship","paths","discover","discover skills","search","10x","terminal",{"skillNo":202,"name":203,"nameZh":204,"description":205,"descriptionZh":206,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":207,"categories":208,"keywords":213,"publishedAt":48},"01M6CD4HQKXNZ57YEGD8QVK6Z6","session-search","会话记录检索","Recall public session turns with exact provenance, bounded excerpts and independent piped exports.","召回公开的会话轮次，附带精确来源、有限摘录和独立的管道导出。","https:\u002F\u002Fgithub.com\u002Fcercova-studios\u002F10x-swe\u002Fblob\u002Fmain\u002Fplugins\u002Fknowledge\u002Fskills\u002Fsession-search\u002FSKILL.md",[209,210],{"categoryNo":158,"categoryName":159,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":211,"categoryName":212,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8C77ZM67V04F92Y3NWFVB3F","会话数据采集与归档",[214,170,198,215,166,165,37,169,216,217,172,218],"session search","bounded","recall","provenance","public"]