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
Python Naming Conventions
Python, known for its simplicity and readability, places a strong emphasis on writing clean and maintainable code. One of the key aspects contributing to this readability is adhering to Python Naming Conventions. In this article, we'll delve into the specifics of Python Naming Conventions, covering
4 min read
Python Exit handlers (atexit)
atexit is a module in python which contains two functions register() and unregister(). The main role of this module is to perform clean up upon interpreter termination. Functions that are registered are automatically executed upon interpreter termination. Whenever a program is killed by a signal not
2 min read
__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
Python Main Function
Main function is like the entry point of a program. However, Python interpreter runs the code right from the first line. The execution of the code starts from the starting line and goes line by line. It does not matter where the main function is present or it is present or not. Since there is no mai
5 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
Importlib package in Python
In this article, we are going to know about the Importlib package in the Python programming language. The importlib package is primarily utilized by Python applications for dynamic imports during runtime. In layman's terms, it allows the user to load modules as he/she discovers them. This package ha
6 min read
Inner Class in Python
Python is an Object-Oriented Programming Language, everything in Python is related to objects, methods, and properties. A class is a user-defined blueprint or a prototype, which we can use to create the objects of a class. The class is defined by using the class keyword.Example of classPython# creat
5 min read
Coroutine in Python
Prerequisite: GeneratorsWe all are familiar with function which is also known as a subroutine, procedure, sub-process, etc. A function is a sequence of instructions packed as a unit to perform a certain task. When the logic of a complex function is divided into several self-contained steps that are
5 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