Langsung ke konten
Skillpedia
Pemrograman umum41k · #6767

python-resource-management

Fungsinya

Skill ini membantu mengelola resource dalam pemrograman Python, memastikan resource tersebut tetap dilepaskan dengan benar meskipun terjadi error. Skill ini berguna untuk menangani koneksi database, file, dan tugas lain yang membutuhkan pembersihan secara teratur.

Kapan dipakai

  • ✓Saat membuka dan menutup koneksi database.
  • ✓Saat membaca atau menulis file.
  • ✓Saat Anda perlu memastikan sesuatu dibersihkan setelah dipakai, misalnya menutup koneksi jaringan.

Link skill

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

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-resource-management/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit →

Contoh permintaan ke AI

“Bagaimana cara memastikan file otomatis tertutup setelah saya selesai menggunakannya di Python?”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Skill ini menggunakan pola yang disebut 'context manager' dengan statement `with`. Pola ini memastikan saat Anda selesai memakai sebuah resource (seperti file atau koneksi), resource tersebut otomatis ditutup atau dilepaskan, bahkan jika terjadi error di tengah jalan.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari 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."""

…
Pertanyaan umum

Apa yang terjadi jika terjadi error saat saya sedang memakai sebuah resource?

Context manager tetap memastikan proses pembersihan (seperti menutup file) dijalankan, meskipun terjadi error. Dengan begitu, resource tidak dibiarkan terbuka tanpa alasan.

Apa itu 'context manager'?

Ini adalah blok kode khusus yang menyiapkan resource sebelum digunakan dan memastikan resource tersebut dibersihkan setelahnya, dengan menggunakan kata kunci `with`.

Apakah ini juga berlaku untuk kode asynchronous (async)?

Ya, tersedia versi khusus untuk kode asynchronous (`async with`) yang bekerja dengan cara yang sama untuk mengelola resource pada operasi yang tidak memblokir program.

Detail

Deskripsi asli dari pembuat

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

Popularitas

Bintang GitHub
41k
Peringkat
#6767
Lisensi
MIT
Diperbarui
15/10/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa