Hackforge Academy

Category: python

Class-based Context Manager

Published on 27 Oct 2026

Explanation

Implement __enter__ for setup and __exit__ for cleanup when a class manages a resource or state.

Code:

class Session:
    def __enter__(self): print('Open'); return self
    def __exit__(self, exc_type, exc_value, traceback): print('Close'); return False
with Session(): print('Work')

Explanation

contextlib.contextmanager lets a generator define setup before yield and cleanup in finally.

Code:

from contextlib import contextmanager
@contextmanager
def resource():
    print('Setup')
    try: yield 'Ready'
    finally: print('Cleanup')
with resource() as value: print(value)

Explanation

A generator context manager can catch exceptions from the managed block at yield. Re-raise unless intentionally handling them.

Code:

from contextlib import contextmanager
@contextmanager
def transaction():
    print('Begin')
    try: yield
    except Exception:
        print('Rollback')
        raise
    else: print('Commit')
with transaction(): print('Work')

Explanation

A context manager can temporarily change a setting and restore the prior state in finally.

Code:

from contextlib import contextmanager
settings = {'debug': False}
@contextmanager
def temporary():
    old = settings['debug']; settings['debug'] = True
    try: yield
    finally: settings['debug'] = old
with temporary(): print(settings['debug'])
print(settings['debug'])

Explanation

A context manager can measure a block's elapsed time with time.perf_counter().

Code:

from contextlib import contextmanager
from time import perf_counter
@contextmanager
def timer():
    start = perf_counter()
    try: yield
    finally: print(perf_counter() - start)
with timer(): sum(range(100_000))

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community