PYTHON · 비동기
비동기 컨텍스트 매니저
async with로 비동기 리소스의 획득과 해제를 안전하게 관리합니다.
비동기중급async with컨텍스트 매니저asynccontextmanager
핵심 설명
async with로 비동기 리소스의 획득과 해제를 안전하게 관리합니다.
Python code
import asyncio
from contextlib import asynccontextmanager
# 클래스 기반 비동기 컨텍스트 매니저
class AsyncConnection:
def __init__(self, host: str):
self.host = host
async def __aenter__(self):
print(f"연결 중: {self.host}")
await asyncio.sleep(0.5) # 연결 시뮬레이션
print(f"연결 완료: {self.host}")
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
print(f"연결 해제: {self.host}")
await asyncio.sleep(0.1)
return False # 예외 전파
async def query(self, sql: str) -> str:
await asyncio.sleep(0.2)
return f"결과: {sql}"
# 함수 기반 (asynccontextmanager)
@asynccontextmanager
async def timer(name: str):
import time
start = time.perf_counter()
try:
yield
finally:
elapsed = time.perf_counter() - start
print(f"{name}: {elapsed:.3f}초")
async def main():
async with AsyncConnection("db.example.com") as conn:
result = await conn.query("SELECT * FROM users")
print(result)
async with timer("작업"):
await asyncio.sleep(1)
asyncio.run(main())학습 팁
asynccontextmanager 데코레이터를 사용하면 __aenter__/__aexit__를 직접 구현하지 않아도 됩니다.
주의할 점
__aexit__에서 True를 반환하면 예외가 억제됩니다. 의도하지 않은 예외 억제를 방지하려면 False를 반환하세요.
자주 묻는 질문
비동기 컨텍스트 매니저란 무엇인가요?
async with 로 비동기 리소스의 획득과 해제를 안전하게 관리합니다.
비동기 컨텍스트 매니저 학습 시 주의할 점은 무엇인가요?
__aexit__ 에서 True 를 반환하면 예외가 억제됩니다. 의도하지 않은 예외 억제를 방지하려면 False 를 반환하세요.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.