Context Manager in Python
Last Updated :
30 May, 2025
In any programming language, the usage of resources like file operations or database connections is very common. But these resources are limited in supply. Therefore, the main problem lies in making sure to release these resources after usage. If they are not released then it will lead to resource leakage and may cause the system to either slow down or crash.
Python’s context managers provide a neat way to automatically set up and clean up resources, ensuring they’re properly managed even if errors occur.
Using the with Statement for File Handling
The simplest way to manage a file resource is using the with keyword:
Python
with open("test.txt") as f:
data = f.read()
This ensures the file is automatically closed once the block is exited, even if an error occurs.
What Happens Without Proper Closing?
If files aren’t closed, you can run out of available file descriptors. For example:
Python
file_descriptors = []
for x in range(100000):
file_descriptors.append(open('test.txt', 'w'))
This will raise:
Traceback (most recent call last):
File "context.py", line 3, in
OSError: [Errno 24] Too many open files: 'test.txt'
Because too many files remain open, exhausting system resource
Why Use Context Managers?
In complex programs, especially those with multiple exit points or exceptions, manually closing files or connections everywhere is error-prone. Context managers automate this cleanup using the with keyword.
Creating a Custom Context Manager Class
A class-based context manager needs two methods:
- __enter__(): sets up the resource and returns it.
- __exit__(): cleans up the resource (e.g., closes a file).
Example:
Python
class ContextManager:
def __init__(self):
print('init method called')
def __enter__(self):
print('enter method called')
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
print('exit method called')
with ContextManager() as manager:
print('with statement block')
Output:
init method called
enter method called
with statement block
exit method called
The above sequence shows how Python initializes the object, enters the context, runs the block, and then exits while cleaning up.
File Management Using Context Manager
Let's apply the above concept to create a class that helps in file resource management. The FileManager class helps in opening a file, writing/reading contents, and then closing it.
Python
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, exc_traceback):
self.file.close()
with FileManager('test.txt', 'w') as f:
f.write('Test')
print(f.closed)
Output:
True
Explanation:
- __enter__() opens the file and returns it.
- Inside the with block, you can use the file object.
- __exit__() ensures the file is closed automatically.
- print(f.closed) confirms the file is closed.
Database Connection Management with Context Manager
Let's create a simple database connection management system. The number of database connections that can be opened at a time is also limited(just like file descriptors). Therefore context managers are helpful in managing connections to the database as there could be chances that the programmer may forget to close the connection.
Python
from pymongo import MongoClient
class MongoDBConnectionManager:
def __init__(self, hostname, port):
self.hostname = hostname
self.port = port
self.connection = None
def __enter__(self):
self.connection = MongoClient(self.hostname, self.port)
return self.connection
def __exit__(self, exc_type, exc_value, exc_traceback):
self.connection.close()
with MongoDBConnectionManager('localhost', 27017) as mongo:
collection = mongo.SampleDb.test
data = collection.find_one({'_id': 1})
print(data.get('name'))
Explanation:
- __enter__() opens the MongoDB connection.
- mongo inside the with block is the client object.
- You can perform database operations safely.
- __exit__() closes the connection automatically.
Similar Reads
__exit__ in Python Context manager is used for managing resources used by the program. After completion of usage, we have to release memory and terminate connections between files. If they are not released then it will lead to resource leakage and may cause the system to either slow down or crash. Even if we do not re
3 min read
Concrete Exceptions in Python In Python, exceptions are a way of handling errors that occur during the execution of the program. When an error occurs Python raises an exception that can be caught and handled by the programmer to prevent the program from crashing. In this article, we will see about concrete exceptions in Python i
3 min read
Context Variables in Python Context variable objects in Python is an interesting type of variable which returns the value of variable according to the context. It may have multiple values according to context in single thread or execution. The ContextVar class present in contextvars module, which is used to declare and work wi
4 min read
Matplotlib.pyplot.rc_context() in Python Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot,
2 min read
Python â The new generation Language INTRODUCTION: Python is a widely-used, high-level programming language known for its simplicity, readability, and versatility. It is often used in scientific computing, data analysis, artificial intelligence, and web development, among other fields. Python's popularity has been growing rapidly in re
6 min read
Code introspection in Python .numpy-table { font-family: arial, sans-serif; border-collapse: collapse; border: 1px solid #5fb962; width: 100%; } .numpy-table td, th { background-color: #c6ebd9; border: 1px solid #5fb962; text-align: left; padding: 8px; } .numpy-table td:nth-child(odd) { background-color: #c6ebd9; } .numpy-table
4 min read
Integrating Java with Python While programming in a language, a developer may feel the need to use some functionality that may have better support in another language. For example, suppose, an application has already been developed in Java, and we wish to use it in Python code. To invoke an existing Java application in Python,
4 min read
PYGLET â Getting Window Context In this article we will see how we can get the window context in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear a
2 min read
Python Built-in Exceptions In Python, exceptions are events that can alter the flow of control in a program. These errors can arise during program execution and need to be handled appropriately. Python provides a set of built-in exceptions, each meant to signal a particular type of error.We can catch exceptions using try and
8 min read
Multithreading in Python This article covers the basics of multithreading in Python programming language. Just like multiprocessing , multithreading is a way of achieving multitasking. In multithreading, the concept of threads is used. Let us first understand the concept of thread in computer architecture. What is a Process
8 min read