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가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
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.
댓글
- …
이 저장소의 다른 스킬
screen-reader-testing
41k에이전트가 스크린 리더로 웹사이트를 테스트해 접근성을 확인하도록 돕습니다.
wcag-audit-patterns
41k에이전트가 WCAG 지침에 따라 웹사이트의 접근성을 감사하고 문제를 고치도록 돕습니다.
multi-reviewer-patterns
41k에이전트가 병렬 코드 리뷰를 조율하고, 중복된 발견 사항을 정리하며, 보고서를 통합하도록 돕습니다.
parallel-debugging
41k에이전트가 병렬 조사와 근본 원인 분석으로 복잡한 문제를 디버그하도록 돕습니다.