Python - Context

Introduction

The with statement allows a developer to create context managers.

They are handy constructs that allow us to set something up and tear something down automatically. For example, we might want to open a file, write a bunch of stuff to it and then close it. This is probably the classic example of a context manager.

In fact, Python creates one automatically for us when we open a file using the with statement:

with open("hello.txt", 'w') as file:
file.write("hello")

The way this works under the covers is by using some of Python’s magic methods: __enter__ and __exit__.

Context Manager

We’ll create a context manager that can create a Python - Sqlite database connection and close it when it’s done.

Here’s a simple example:

contextlib

The Python contextlib module provides utilities for working with context managers, which allows you to allocate and release resources precisely.

This module is especially useful for creating context managers and managing resources in a clean and safe way.

Here’s a quick toy example:

from contextlib import contextmanager
@contextmanager
def context():
print("Entering")
yield
print("Exiting")
with context():
print("Inside")
Entering
Inside
Exiting

Pending

contextlib Context Manager and Contextlib in Python