Loading

Quipoin Menu

Learn • Practice • Grow

python / Context Managers
tutorial

Context Managers

Context managers allow you to allocate and release resources precisely. The `with` statement is used to wrap a block with setup and teardown actions. You can create your own context managers using the `contextlib` module or by implementing `__enter__` and `__exit__`.

Using `with` for Files (Built‑in)
Files are already context managers.


with open("file.txt", "r") as f:
data = f.read()
# file is automatically closed

Creating a Custom Context Manager (Class)
Implement `__enter__` and `__exit__`.


class ManagedFile:
def __init__(self, name, mode):
self.name = name
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.name, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()

with ManagedFile("hello.txt", "w") as f:
f.write("Hello, World!")

Using `contextlib.contextmanager`
Simpler way with generator.


from contextlib import contextmanager

@contextmanager
def managed_file(name, mode):
f = open(name, mode)
try:
yield f
finally:
f.close()

with managed_file("test.txt", "w") as f:
f.write("Data")
Two Minute Drill
  • Context managers handle setup/teardown, often with `with`.
  • Create by defining `__enter__`/`__exit__` or using `contextlib.contextmanager`.
  • `with` ensures resources are cleaned up even if an exception occurs.
  • Useful for files, locks, database connections.

Need more clarification?

Drop us an email at career@quipoinfotech.com