Python Context Manager

Table Of Contents:

  1. What Is Context Management?
  2. Benefits Of Context Management.
  3. Context Management Using ‘try’ with ‘finally’ Approach.
  4. Context Management Using ‘with’ statement.
  5. Context Management Using ‘__enter__()’ and ‘__exit__()’ method.

(1) What Is Context Management?

  • When you finished using something, you should keep that thing in its place, so that the next person can find it easily.
  • Suppose after using your car key you through it somewhere in your house, next time when you want to drive it you won’t find it.
  • So it is better to keep things in their place after using them.
  • So in Python also same rules apply. After using some resources like flies, memories, CPU etc. you should release them for another program to use.

(2) Benefits Of Context Management?

  • Context management helps us to release recourses after using them.
  • It increases system performance by closing all unused resources like files, database connections, CPU uses etc.
  • It prevents memory leaks because the available memory gets reduced every time you create and open a new instance of a given resource without closing an existing one.
  • Context Manager helps us to do cleanup actions, such as closing a file, releasing a lock, or closing a network connection.

(3) Context Management Using ‘try’ with ‘finally’ Approach.

  • You can use ‘try’ with the ‘finally’ block to do the context management.
  • Do all your operation on the ‘try’ block and use the ‘finally’ block for the cleaning operation.
  • Because the ‘finally’ block will be called always no matter what happens to your code in the ‘try’ block.
  • Hence your clean-up activity will be executed every time.

Example

try:
    print('File Opened !')
    file = open('hello.txt','r')
    print(file.read())

except FileNotFoundError as err:
    print('File Not Found Error',err)
    
finally:
    file.close()
    print('File Closed !')
Output:
File Opened !
Hello World ! 
File Closed !

Note:

  • In the above program, we are opening a file in the ‘try’ block and close the file in the ‘finally’ block.

(4) Context Management Using ‘with’ Statement.

  • ‘with’ statement is the alternative of the ‘try‘ and ‘finally’ block.
  • Compared to traditional try …. finally constructs, the ‘with’ statement can make your code clearer, safer, and reusable.
  • The ‘with’ keyword is used while opening the connection and you can write your code within the ‘with‘ block.
  • The ‘with’ statement automatically closes the connection after you’ve completed writing it.

Example

with open('hello.txt','r') as file:
    print(file.read())
Output:
Hello World ! 

Note:

  • Here you can see that it took fewer lines of code to handle the file operation.
  • With statement will automatically close the file at the end.

(5) Context Management Using ‘__enter__()’ and ‘__exit__()’ method.

  • You can create your own context manager class and do your own clean-up activity.
  • You can use the __enter__() and __exit__() method to implement the context management.
  • __enter__() is called by the ‘with’ statement to enter the runtime context.
  • __exit__() is called when the execution leaves the ‘with’ code block.

Example

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

Note:

  • __enter__() is called by the ‘with’ statement to enter the runtime context.
  • __exit__() is called when the execution leaves the ‘with’ code block.

Leave a Reply

Your email address will not be published. Required fields are marked *