本文へスキップ
Skillpedia
一般的なプログラミング41k · #6767

python-resource-management

できること

このスキルは、Pythonプログラミングにおけるリソースの管理を助けるものです。エラーが発生しても、リソースが確実に解放されるようにします。データベース接続やファイルなど、整理された後片付けが必要な処理に役立ちます。

使う場面

  • ✓データベース接続を開いたり閉じたりするとき。
  • ✓ファイルの読み込みや書き込みを行うとき。
  • ✓ネットワーク接続を閉じるなど、使用後に確実に後片付けを行う必要があるとき。

スキルのリンク

https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-resource-management/SKILL.md

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-resource-management/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“Pythonでファイルを使い終わったら自動的に閉じるようにするには、どうすればよいですか?”

毎週5つの新しいスキル。1分で読めます。

仕組み

「with文」を使ったコンテキストマネージャーというパターンを利用します。リソース(ファイルや接続など)の使用が終わると、途中でエラーが起きても自動的に閉じたり解放されたりするようになります。

技術的な内容(元のSKILL.md)

作者による元のテキスト(英語)をGitHubからそのまま表示しています。

Python Resource Management

Manage resources deterministically using context managers. Resources like database connections, file handles, and network sockets should be released reliably, even when exceptions occur.

When to Use This Skill

  • Managing database connections and connection pools
  • Working with file handles and I/O
  • Implementing custom context managers
  • Building streaming responses with state
  • Handling nested resource cleanup
  • Creating async context managers

Core Concepts

1. Context Managers

The with statement ensures resources are released automatically, even on exceptions.

2. Protocol Methods

__enter__/__exit__ for sync, __aenter__/__aexit__ for async resource management.

3. Unconditional Cleanup

__exit__ always runs, regardless of whether an exception occurred.

4. Exception Handling

Return True from __exit__ to suppress exceptions, False to propagate them.

Quick Start

from contextlib import contextmanager

@contextmanager
def managed_resource():
    resource = acquire_resource()
    try:
        yield resource
    finally:
        resource.cleanup()

with managed_resource() as r:
    r.do_work()

Fundamental Patterns

Pattern 1: Class-Based Context Manager

Implement the context manager protocol for complex resources.

class DatabaseConnection:
    """Database connection with automatic cleanup."""

    def __init__(self, dsn: str) -> None:
        self._dsn = dsn
        self._conn: Connection | None = None

    def connect(self) -> None:
        """Establish database connection."""
        self._conn = psycopg.connect(self._dsn)

    def close(self) -> None:
        """Close connection if open."""
        if self._conn is not None:
            self._conn.close()
            self._conn = None

    def __enter__(self) -> "DatabaseConnection":
        """Enter context: connect and return self."""
        self.connect()
        return self

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Exit context: always close connection."""
        self.close()

# Usage with context manager (preferred)
with DatabaseConnection(dsn) as db:
    result = db.execute(query)

# Manual management when needed
db = DatabaseConnection(dsn)
db.connect()
try:
    result = db.execute(query)
finally:
    db.close()

Pattern 2: Async Context Manager

For async resources, implement the async protocol.

class AsyncDatabasePool:
    """Async database connection pool."""

    def __init__(self, dsn: str, min_size: int = 1, max_size: int = 10) -> None:
        self._dsn = dsn
        self._min_size = min_size
        self._max_size = max_size
        self._pool: asyncpg.Pool | None = None

    async def __aenter__(self) -> "AsyncDatabasePool":
        """Create connection pool."""
        self._pool = await asyncpg.create_pool(
            self._dsn,
            min_size=self._min_size,
            max_size=self._max_size,
        )
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Close all connections in pool."""
        if self._pool is not None:
            await self._pool.close()

    async def execute(self, query: str, *args) -> list[dict]:
        """Execute query using pooled connection."""
        async with self._pool.acquire() as conn:
            return await conn.fetch(query, *args)

# Usage
async with AsyncDatabasePool(dsn) as pool:
    users = await pool.execute("SELECT * FROM users WHERE active = $1", True)

Pattern 3: Using @contextmanager Decorator

Simplify context managers with the decorator for straightforward cases.

from contextlib import contextmanager, asynccontextmanager
import time
import structlog

logger = structlog.get_logger()

@contextmanager
def timed_block(name: str):
    """Time a block of code."""
    start = time.perf_counter()
    try:
        yield
    finally:
        elapsed = time.perf_counter() - start
        logger.info(f"{name} completed", duration_seconds=round(elapsed, 3))

# Usage
with timed_block("data_processing"):
    process_large_dataset()

@asynccontextmanager
async def database_transaction(conn: AsyncConnection):
    """Manage database transaction."""

…
よくある質問

リソースを使用中にエラーが発生したらどうなりますか?

コンテキストマネージャーにより、エラーが起きても後片付け(ファイルを閉じるなど)が実行されます。これにより、不必要にリソースが開いたままになるのを防げます。

「コンテキストマネージャー」とは何ですか?

`with`キーワードを使い、リソースを使用する前に準備を行い、使用後に後片付けを確実に行う特別なコードブロックのことです。

非同期(async)のコードでも使えますか?

はい。非同期コード用の`async with`という専用の書き方があり、処理をブロックしない形でリソースを管理できます。

詳細

作者による元の説明

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.

repo: wshobson/agents

人気

GitHubのスター
41k
ランキング
#6767
ライセンス
MIT
更新日
2026/10/15

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル