Context Manager Protocol

Get details on context manager in Python.

Introduction

Brush up, when we talk about Python being humble with the for loop. Behind the curtains, we have iterators working. Likewise, context managers exist to control a with statement. Whereas, the with statement was introduced to simplify the try/finally pattern.

❗️ Note: The try/finally pattern won’t be discussed here. We expect that you know how it works. In case you are new to it, please refer to the official documentation.

Before jumping directly to context managers, let’s have a quick overview of the with statement.

Overview of with statement

The syntax of the with statement looks as:

with expression [as variable]:
  with-block

When this expression is evaluated, it gives an object that supports the context management protocol. This prompts the question: what is a context management protocol?

An object that backs up the context management protocol is the one that supports two dunder methods: __enter__() and __exit__().

The __enter__() method is called before with-block is executed. After the execution of with-block, the __exit__() method is called, even if the block (the with block) raised an exception.

⚙️ To enable with in Python 2.5, you need to add a line in your code: from __future__ import with_statement. The statement will always be enabled in Python 2.6 and later.

Let’s devise a basic demo of the with statement.

Example

Get hands-on with 1200+ tech skills courses.