DEV Community

Nicholus Mush
Nicholus Mush

Posted on

Context Managers with in Python

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())
Enter fullscreen mode Exit fullscreen mode

Context managers keep code concise and safe for resources like files and locks.

Top comments (0)