Trung BìnhPython iconPython

Context Manager và `with` statement hoạt động thế nào?

Context manager quản lý tài nguyên tự động qua __enter____exit__. with đảm bảo cleanup chạy dù có exception hay không.

python
from contextlib import asynccontextmanager

# Dùng @asynccontextmanager cho async code (không phải @contextmanager)
@asynccontextmanager
async def db_transaction(session):
    try:
        yield session
        await session.commit()
    except Exception:
        await session.rollback()
        raise

# Class-based (sync)
class Timer:
    def __enter__(self):
        import time; self.start = time.perf_counter(); return self
    def __exit__(self, *args):
        self.elapsed = time.perf_counter() - self.start

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python