The Wayback Machine - https://web.archive.org/web/20240821214909/https://www.geeksforgeeks.org/reusable-piece-of-python-functionality-for-wrapping-arbitrary-blocks-of-code-python-context-managers/
Open In App

Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers

Last Updated : 01 Aug, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guarantees the exit. So, without any procrastination, lets dive and acquire the new mantra for resource cleanliness without the code repetition.

Context Managers

Context Managers

Note: Knowledge about Decorators and Generators is appreciated

Context Manager Syntax

As we all know, the proper way to release the resource is by closing the resource after its use. And the most common practice followed to structure the close function is by using Exception Handling. Let’s look into the below code.




def main():
    try:
        file = open('sample.txt', 'r')
        data = file.read()
        print(data)
    finally:
        file.close()
  
main()


The finally clause ensures that the file will be closed irrespective of any situation. But this process results in code repetition. So, how you achieve the same using Context Manager without the boilerplate setup. Let’s go through the below sections one by one:

  • The with statement
  • The enter and exit method
  • Exception Handling

The with statement

with statement, the python built in function can be used as a context manager.




with open (‘filename’, ’r’)  as file:
    data = file.read()


This code performs the same functionality of what we developed using exception handling. Here the with statement is expected to return an object with two magic methods: __enter__ and __exit__. The result returned from __enter__ method is assigned to the variable mentioned after the `as` keyword.

It handles if an exception is raised within the wrapped code and most importantly the statement ensures that the resource is released. So, the programmers need not perform the close operation. Here is the full code.




def main():
    with open('sample.txt', 'r') as file:
        data = file.read()
        print(data)
  
main()


The enter and exit method

The __enter__ method returns an object, and then the returned value is assigned to the variable mentioned after the `as` keyword. Other than self argument it takes no other arguments.
On the other hand, the __exit__ method takes 3 positional arguments other than self argument. By default, these three arguments are none and are populated with information when the wrapped code raises an exception.

The below code explains the workflow of the Context Manager. Keep a note of the inside attribute and How the attribute value changes in different scenarios. Upon entering the context manager, the attribute value is set to true and on exit,  its value is set to false. Once the block of code within the with statement completes execution the __exit__ method gets invoked.




class ContextCheck(object):
      
    def __init__(self):
        self.inside = False
  
    def __enter__(self):
        self.inside = True
        return self
  
    def __exit__(self, exc_type, exc_instance, traceback):
        self.inside = False
  
  
cntCheck = ContextCheck()
print(cntCheck.inside)
  
with cntCheck:
    print(cntCheck.inside)
  
print(cntCheck.inside)


Output

False
True
False

Exception Handling

How the exception is handled using the Context Manager?
Using the __exit__ method, the context manager handles exceptions that are raised by the wrapped code. __exit__ method has 3 positional arguments:

  • Type of the Exception
  • An instance of the Exception
  • Traceback option

By default, all three values are None. When an __exit__ method receives an exception, the method can handle the exception in 2 different ways:

  • Re-raise the exception
  • Suppress the exception

Re-raise the exception

The __exit__ method can re-raise the exception by having a return statement that returns False. Let’s see the below code:




class BubbleExc(object):
    def __enter__(self):
        return self
  
    def __exit__(self, ex_type, ex_instance, traceback):
        if ex_instance:    
            print('Exception: % s.' % ex_instance)
        return False
  
with BubbleExc():
    1 / 0


Output

Exception: division by zero.
Traceback (most recent call last):
  File "C:\Users\Sonu George\Documents\Python\Context Managers\bubbleExc.py", line 11, in 
    1/0
ZeroDivisionError: division by zero

Suppress the exception

The __exit__ method can suppress the exception by returning true. See the below example for detailed understanding.




class SuppressExc(object):
    def __enter__(self):
        return self
  
    def __exit__(self, ex_type, ex_instance, traceback):
        if ex_instance:
            print('Suppressing exception: % s.'% ex_instance)
        return True
  
with SuppressExc():
    1 / 0


Output>

Suppressing exception: division by zero.

When you should write Context Managers

  • Releasing the Resources: Releasing the resources often ends up with boilerplate code. Using Context Managers, programmers can open the resource in the __enter__ method and close it in the __exit__ method and can reuse the functionality on demand.
  • Avoid Repetition: Exception Handling using except clause results in repetitive code. Using Context Manager, programmers can either raise or suppress the exception, and importantly it is defined in one place and hence can avoid repetition.

Writing Context Manager

Knowing is not enough; we must apply. Willing is not enough; we must do.
– Johann Wolfgang von Goethe

Implementing a Context Manager as a Class

A sample method that writes to a file using Context Manager. Here is the full code.




class FileClass(object):
      
    def __init__(self, f_name, func):
        self.f_obj = open(f_name, func)
          
    def __enter__(self):
        return self.f_obj
  
    def __exit__(self, type, value, traceback):
        self.f_obj.close()
  
with FileClass('sample.txt', 'w') as f_open:
    f_open.write('Congratulations, Good Work !')


Output

Congratulations, Good Work!

Closing a page using Context Manager

Here the page.close() will be called after completion of reading the page (upon exit from the with block).




from contextlib import closing
from urllib.request import urlopen
  
with closing(urlopen('https://www.geeksforgeeks.org/')) as page:
    for ln in page:
        print(ln)


Output


Using a Context Manager as a function Decorator and Generator

With the python contexlib module, you can implement context manager as decorator and the yield statement within the method gives the flexibility to use it as a generator. To understand this program, you should have prior knowledge about decorators and generators.




from contextlib import contextmanager
  
@contextmanager
def open_file(name):
    try:
        print('File Open')
        f = open(name, 'r')
        yield f
    finally:
        print('Close Operation')
        f.close()
  
  
  
def main():
    with open_file('sample.txt') as f:
        data = f.read()
        print(data)
main()


Here @contextmanager wraps the open_file method. When the function open_file gets invoked, the __enter__method of the context manager executes and pass the control to open_file method where the file opens and yield the file reference to callable with open_file('sample.txt') as f and the execution halts before executing the finally block.  

Once the code within the with statement is executed, it passes the control back to the open_file and the execution begins from where it is halted. In this case, the finally block executes and closes the file. Upon completion of execution, the __exit__ method is called and it handles any exception that is raised by the wrapped code.

Handling exception by checking instance of an Exception Class

In this case, we will check whether an exception is an instance of an exception class. Below we will create a subclass ‘TypeErrorSubclass’, which is derived from the ‘TypeError’ exception class, and using the raise statement we will raise the ‘TypeErrorSubclass’ exception. Here is the full code.




class TypeErrorSubClass(TypeError):
    pass
  
  
class ExceptionClass(object):
    def __enter__(self):
        return self
  
    def __exit__(self, ex_type, ex_instance, traceback):
        # Return True if there is no exception
        if not ex_type:
            return True
  
        # Return True if execution type is
        # equal or a subclass of TypeError
        if issubclass(ex_type, TypeError):
            print('Handling TypeError: % s' % ex_instance)
            return True
  
        return False
  
with ExceptionClass():
    raise TypeErrorSubClass('Type Error')


Output

Handling ValueError: Type Error

The __exit__ method checks if the exception raised is an instance of ‘TypeError’ class using issubclass(ex_type, TypeError), and if it’s an instance then suppress the exception by returning True.

Summary

Context managers ensure resources are released properly and the way it’s structured provides the flexibility of re-using the exception handling code at different places and hence avoid code repetition. Context managers are used for wrapping arbitrary blocks of code. However, a Context Manager can be used as a decorator, which avoids the need for writing a Context Manager and a Decorator separately for certain tasks.



Similar Reads

Textwrap – Text wrapping and filling in Python
The textwrap module can be used for wrapping and formatting of plain text. This module provides formatting of text by adjusting the line breaks in the input paragraph. The TextWrapper instance attributes (and keyword arguments to the constructor) are as follows: width: This refers to the maximum length allowed of the wrapped lines. It's default val
6 min read
Wrapping C/C++ for Python using SWIG - Set 1
There is no doubt that C is faster than Python then how do Python library like Numpy perform huge number crunching job so fast and efficiently? Actually, libraries like Numpy are not completely written in Python instead, some parts of the library are written in C which provides performance boost. After writing code in C, we wrap them in Python code
5 min read
PyQt5 QSpinBox - Allowing wrapping the value
In this article we will see how we can make the spin box to make wrapping the value. Wrapping will make the stepping up from maximum value change value to the lowest value, similarly stepping down from minimum value change value to the maximum value just like cycle. Note : Wrapping only make sense if you have minimum and maximum values are set. In
2 min read
PyQt5 QSpinBox - Checking if wrapping is allowed
In this article we will see how we can check if wrapping is allowed in the spin box or not. Wrapping will make the stepping up from maximum value change value to the lowest value, similarly stepping down from minimum value change value to the maximum value just like cycle. We can make the wrapping allowed in the spin box with the help of setWrappin
2 min read
PyQt5 QDial - Setting Wrapping Property
In this article we will see how we can set the wrapping property of the QDial. By default when we create a QDial there is some space between the minimum and maximum value, we can remove this space by enabling wrapping property otherwise some space is inserted at the bottom of the dial to separate the ends of the range of valid values. In order to d
2 min read
PyQt5 QDial - Getting Wrapping Property
In this article we will see how we can get the wrapping property of the QDial. By default when we create a QDial there is some space between the minimum and maximum value, By enabling wrapping property we can remove the extra space otherwise some space is inserted at the bottom of the dial to separate the ends of the range of valid values. Wrapping
2 min read
PyQt5 QDateTimeEdit – Setting Wrapping Property
In this article we will see how we can set wrapping property of the QDateTimeEdit widget. QDateTime is basically a combination of QDate and QTime i.e it has both date and time. And QDateTimeEdit widget is used to show or receive the QDateTime. Wrapping property makes stepping up from maximum date time will take user to the minimum date time and vic
2 min read
PyQt5 QDateTimeEdit – Getting Wrapping Property
In this article we will see how we can get wrapping property of the QDateTimeEdit widget. QDateTime is basically a combination of QDate and QTime i.e it has both date and time. And QDateTimeEdit widget is used to show or receive the QDateTime. Wrapping property makes stepping up from maximum date time will take user to the minimum date time and vic
2 min read
Text box with line wrapping in Matplotlib
Matplotlib is a majorly used python comprehensive library for visualization(static, animated, creative & interactive). It provides a wide range of methods for annotating and describing the plot through text. Also, it can wrap the text automatically. Text is used in a plot for various purposes Aside from describing the plot, the other use for te
3 min read
Modify Numpy array to store an arbitrary length string
NumPy builds on (and is a successor to) the successful Numeric array object. Its goal is to create the corner-stone for a useful environment for scientific computing. NumPy provides two fundamental objects: an N-dimensional array object (ndarray) and a universal function object (ufunc). The dtype of any numpy array containing string values is the m
3 min read
How to capture arbitrary paths at one route in FastAPI
FastAPI is a modern Python framework for building scalable APIs. It is fast, easy to use, and allows the creation of robust APIs. In this article, we will see how to capture arbitrary paths at one route in FastAPI. Capture Arbitrary Path in FastAPIIn FastAPI, arbitrary paths can be captured using the Path parameters. Path parameters allow you to de
2 min read
Built in & Custom Model Managers in Django
Django manager is a class that acts as an interface through which Django models interact with databases. Every model has at least one manager object. It has a lot of methods, attributes to ease working with databases. In fact, many beginner-level Django developers do not know that they use the Manager class object to extract or create desired model
6 min read
Python | Pandas DataFrame.blocks
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas. Pandas DataFrame.blocks attribute is
2 min read
Python - API.blocks() in Tweepy
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user.
2 min read
BEGIN and END Blocks In Ruby
Every Ruby source file can run as the BEGIN blocks when the file is being loaded and runs the END blocks after the program has finished executing. The BEGIN and END statements are different from each other. A program may contain multiple BEGIN and END blocks. If there is more than one BEGIN statement in a program, they are executed in the order If
2 min read
Context Manager in Python
Managing Resources: 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 syste
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 with context variables in python. Note: This is supp
4 min read
Context Manager Using @contextmanager Decorator
Decorators are very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it. Syntax: @decorator def function(args): statements(s) Example: C/C++ Code # Python program
3 min read
PyQt5 QCalendarWidget - Setting Context Menu Policy to it
In this article we will see how we can set the context menu policy to the QCalendarWidget. Context menu policy tells how the calendar will show the context menu, there are many policies available for the calendar like NoContextMenu, PreventContextMenu etc. By default calendar has DefaultContextMenu as context policy. In order to do this we will use
1 min read
PyQt5 QCalendarWidget - Getting Context Menu Policy of it
In this article we will see how we can get the context menu policy of the QCalendarWidget. Context menu policy tells how the calendar will show the context menu, there are many policies available for the calendar like NoContextMenu, PreventContextMenu etc. By default calendar has DefaultContextMenu as context policy although we can change this with
2 min read
PYGLET – Making Window Current OpenGL rendering context
In this article we will see how we can make the window current opengl rendering context in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or ca
2 min read
PYGLET – On Context State Lost Event
In this article we will see how we can trigger on context state lost event in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to f
2 min read
PYGLET – On Context Lost Event
In this article we will see how we can trigger on context lost event in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an
2 min read
PYGLET – Getting Window Context
In this article we will see how we can get the window context in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire
2 min read
PyCairo - How to Create Context Object
In this article we will see how we can create context object in pycairo python. Pycairo is a Python module providing bindings for the cairo graphics library. This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edg
2 min read
PyCairo - Setting Context Color
In this article, we will see how we can set context colors in pycairo Python. Pycairo is a Python module providing bindings for the Cairo graphics library. This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge,
3 min read
How to Pass Additional Context into a Class Based View (Django)?
Passing context into your templates from class-based views is easy once you know what to look out for. There are two ways to do it - one involves get_context_data, the other is by modifying the extra_context variable. Let see how to use both the methods one by one. Explanation: Illustration of How to use get_context_data method and extra_context va
2 min read
Historical context and evolution of CGI.
When you click on any of the links on the webpage, your browser contacts the HTTP web server and demands the URL that is, the filename, and the web server passes the URL and looks for the filename, if it finds that file, it will send it back to the browser otherwise sends an indicating message that you have requested a wrong file. Then, the web bro
12 min read
Top 10 Python Built-In Decorators That Optimize Python Code Significantly
Python is a widely used high-level, general-purpose programming language. The language offers many benefits to developers, making it a popular choice for a wide range of applications including web development, backend development, machine learning applications, and all cutting-edge software technology, and is preferred for both beginners as well as
12 min read
Python code to move spaces to front of string in single traversal
Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once. Examples: Input : str = "geeks for geeks" Output : str = " geeksforgeeks" Input : str = "move these spaces to beginning" Output : str = " movethesespacestobeginning" There were four space characters in input, a
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg