Sitemap

Member-only story

Context Managers in Python

3 min readJun 10, 2024

--

Press enter or click to view image in full size
Photo by David Clode on Unsplash

Today, I will be discussing about Context Managers. I like to keep my articles concise to avoid taking more time from my fellow developers. Without further ado, let’s get started.

Definition in Simple terms

Context Manager is nothing more than an Object. It allows us to properly manage resources so that we can avoid open file handles, connections or any other resources that should be closed or released.

How to use Context Managers

The with keyword simplifies the process. In below example, with keyword is used to open a file. This ensures that the file is closed after it is no longer needed.

with open('file.txt', 'r') as f:
file_contents = f.read()

With the help of with keyword, we don’t have to worry about forgetting to close the file. It automatically takes care of that so it makes our life a little easier. 🙂

Creating custom Context Managers

There are mainly two approaches to create our own custom context managers.

  1. Class based
  2. Generator based

Let’s discuss these one by one.

1. Class based context managers

--

--

Gagan
Gagan

Written by Gagan

Full stack developer exploring new technologies