Menu Close

Context Manager in Python

Context Manager in Python

In this tutorial, you will learn everything about Context Manager in Python with the help of examples like how to create Python context managers and how to use them with the help of proper examples.

Introduction of Context Manager in Python

Python provides a concept of a context manager that enables developers to execute the concept of context manager to manage the resources.

In programming languages, Resources are widespread but these resources are limited to supply so it’s better to close the resources after usages these resources. If these resources are not closed after its usages it leads to the resources and causes the system to crash or slow down. So it’s better options to close the resources once its usage for example database connection, file handling, etc.

Managing Resouces using Context Managers

Suppose a block of code raises an exception or it has a complex algorithm to multiple return statements, Then it is complex to close all the files in all the places. That’s why Python provides a concept of context managers that are used to manage the resources.
Context Manager is used with with statements in Python. Python context manager can be written using classes or functions.

Creating a Python Context Manager

When creating a context manager using classes it must ensure that the class has the following methods.

  • __enter()__:- This method returrn the resouces that need to be manage.
  • __exit()__:- __exit()__ does not return the naything but cleanup the resoucses.

Let’s create our first Python context manager called ContextManager to understand what exactly going on in process of creating a python context manager.

Example:- Creating Python Context Manager


# Create context manager
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")
    
    
 
# Use Context Manager
with ContextManager() as manager:
    print("with statement block!")

Output


Init Method Called
Enter Method Called
with statement block!
Exit Method Called

File Management Using Context Manager

Here we are going to create a class-based context manager that is capable of managing file-related operations such that open a file and read the file as well as the write contents to the file. This context manager’s name will be FileContextManager.

Example: file management using a context manager


# Create context manager
class FileContextManager:

    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()
    
    
 
# Use Context Manager
with FileContextManager("simple.txt", "r") as ff:
    data = f.read()
    print(data)
    
file.close()

Breakdown The Above Code

  • First, we create a class based Context Manager named FileContextManager.
  • Second, FileContextManager object is created when __init__ method is excecuted with simple.txt file name and r mode.
  • Third, The __enter__ method open the simple.txt file with read operatiorn and return the FileContextManager object as f.
  • Fourth, All the content stored inside data variable.
  • Fifth, The __exit__ method is responsible for closing the file and exit from block.

Database Connection Management with Context Manager

Most of the time we need to connect our Python application with databases, Then we can create our own Context manager for database management. The context managers are really helpful for managing database connections.

Let’s create a Context Manager that is capable for manage MySQL Database connections.

Example

import mysql.connector
# Create context manager
class MySQLConnectionManager:

    def __init__(self, hostname, username, password, database, port):
        self.host = hostname
        self.username = username
        self.password = password
        self.database = database
        self.port = port
        self.connection = None
      
    def __enter__(self):
        self.connection = mysql.connector.connect(host=self.host, user=self.username, password=self.password, database=self.database, port=self.port)
        return self.connection
        
        
    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.connection.close()
    
    
 
# Use Context Manager
with MySQLConnectionManager("localhost", "root", "root21", "college", 3308) as mysqldb:
    mycursor = mysqldb.cursor()
    mycursor.execute("SELECT * FROM student")
    students = mycursor.fetchall()
    for st in students:
        print(st)
        
    mycursor.close()

Output


(1, 'Vishvajit Rao', 'Bangalore', 'BCA', 70)
(2, 'Vipul', 'Delhi', 'BCA', 90)
(3, 'Vaibhav', 'Lucknow', 'BTech', 60)
(4, 'Shivani', 'Lucknow', 'BTech', 65)
(5, 'Mohit', 'Delhi', 'BPharma', 70)
(6, 'Shivam Kumar', 'Lucknow', 'BCA', 100)
(7, 'Harprit', 'Delhi', 'BTech', 150)
(8, 'Harprit Kaur', 'Delhi NCR', 'BTech CS', 90)
(9, 'Rashee', 'Bangalore', 'MCA', 90)
(10, 'Vikas Yadav', 'Noida', 'MTech', 500)

Click here to install a Python MySQL connector.

Breakdown The Above Code

  • MySQLConnectionManager represent the Context manager name.
  • The __init__ method will excecute when object of MySQLConnectionManager is created and assign the values of host, username, password, database and port.
  • The __enter__ method establish the connection and return the connection.
  • The __exit__ method is capable of close the connection and exit.
  • Used MySQLConnectionManager with with keyword and pass values of host, username, password, database and port.
  • Define a cursor object named mycursor using mysqldb.cursor().
  • Execute a sql query SELECT * FROM student to select all the records from student table using mycursor.execute() method.
  • Now fetch all the students using mycursor.fetchall().
  • And after that we have used Python for loop to iterate each object.

Conclusion

So, in this article, we have seen all about Python context manager with the complete process to create custom context manager with the help of examples. Context manager in Python is one of the most important concepts to manage resources. the init, enter and exit functions are the important function to create a Python context manager.

If you like this article, please share and keep visiting for further Python tutorials.


What is the Context Manager in Python?

Ans:- Python context manager allows developers to allocate and release resources precisely whenever they want.

How do you write a context manager in Python?

Ans:- Context manager in Python contains generally two magic methods enter and exit method. The with statement in Python is also responsible for calling the context manager.

Thanks for your valuable time …. 👏👏👏

Previous Article
Next Article

Related Posts