Skip to content

Context Manager

Fitri edited this page Sep 6, 2021 · 11 revisions

Introduction to Context Managers

Context managers is the most efficient way of managing python resources, we can set open method which will initialized the resources and once we done any process we can directly exit and context managers will automatically close down the resources. This is very useful to handle program with huge memory along with generator.

Resources

The Function without Context Managers

Built-in Context Manager Object

Normal Generator Function

In order to create context manager with decorator, we need to use the function generator. In here define a simple function generator which will yield empty value.

The reason for the empty yield is the code will replace the yield with any code we include when we call this function using 'with' keyword.

Creating a function which will perform the method __enter__ and __exit__ using contextmanager from contextlib module:

def function_generator(n):
    print("This is enter action")
    yield #this code will be replace with whatever code we include when call this using 'with' keyword
    print("This is exit action")

Now lets try call the function using 'with' keyword and inside it we pass a simple print message:

with function_generator():
    print('Hi') #this code will be print in place of 'yield'

How the output will look like?

This is enter action
Hi
This is exit action

Creating Context Manager with Class

Context Manager with Decorator

Clone this wiki locally