Hackforge Academy

Category: python

What Is a Context Manager?

Published on 27 Oct 2026

Explanation

A context manager performs setup and cleanup around a block. with invokes exit behavior even when an exception occurs.

Code:

with open('example.txt', 'w', encoding='utf-8') as file:
    file.write('Learning Python')

Explanation

Using with ensures a file is closed when the block exits, including when an exception occurs.

Code:

with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
print(file.closed)

Explanation

Class-based context managers implement __enter__ and __exit__. Returning True from __exit__ suppresses an exception, so do this only intentionally.

Code:

class Demo:
    def __enter__(self): print('Enter'); return self
    def __exit__(self, exc_type, exc_value, traceback):
        print('Exit')
        return False
with Demo(): print('Inside')

Explanation

A single with statement can manage multiple resources; exit occurs in reverse order of entry.

Code:

with open('input.txt', encoding='utf-8') as source, open('output.txt', 'w', encoding='utf-8') as target:
    target.write(source.read())

Explanation

contextlib provides tools for creating and composing context managers, including redirect_stdout for capturing print output.

Code:

from contextlib import redirect_stdout
from io import StringIO
buffer = StringIO()
with redirect_stdout(buffer): print('Captured')
print(buffer.getvalue())

πŸš€ 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