Member-only story
Context Managers in Python
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.
- Class based
- Generator based
Let’s discuss these one by one.








