Context Manager in Python using @contextmanager decorator

In this tutorial, we are going to discuss the context manager in Python using @contextmanager decorator.
But first, we need to understand what is context manager in detail.

Python provides users one special tool to modify the behavior of the class. The behavior of the function can be
changed also, it depends upon the requirements of the user. It provides us a facility to wrap the functions.
This means in detail we can wrap any different functions so that we can extending the ability of our running function.

Syntax:

@decorator
def function(args):
  statements(v)

Now we will take a look at context manager

In Python, we generally deal with the file as a resource manager. But context manager can be stated as a resource manager.
We generally don’t care about ending the files, but that’s just unacceptable because it is a bad habit for a programmer.
In such a case context manager helps us out through this situation. The “with” keyword is used in such a situation.

Code for a context manager program in Python

from contextlib import contextmanager 
@contextmanager
def Cmanager(): 
  print("First method is called.") 
  yield
  
  print("Last method is called.") 

with Cmanager() as manager: 
  print('Important statements in the block.') 
Output:
First method is called.
Important statements in the block.
Last method is called.

You can also be referred to:

Leave a Reply

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