title: Context Managers & with in Python
published: false
tags: [python, context-managers]
Context managers handle setup/teardown reliably using with blocks.
This post shows how to use built-ins like file objects and how to create
custom managers with __enter__/__exit__ or contextlib.contextmanager.
Example:
from contextlib import contextmanager
@contextmanager
def open_read(path):
f = open(path)
try:
yield f
finally:
f.close()
with open_read('data.txt') as f:
print(f.readline())
Context managers keep code concise and safe for resources like files and locks.
Top comments (0)