Python – What are Context Managers?

What are Context Managers?

Context managers are constructs that allow you to set something up and tear something down automatically, by using using the statement – with.  For example you may want to open a file, write to the file, and then close the file.

Here is an example of a context manager,

with open(path, 'w') as f_obj:
    f_obj.write(some_data)

To perform this without using a context manager you would need to do,

f_obj = open(path, 'w')
f_obj.write(some_data)
f_obj.close()

Under the hood context managers use the magic methods __enter__ and __exit__.

Context Manager Class

The first way you can build a context manager is by creating a class and using the __enter__ and __exit__ magic methods, like so,

class FileOpen(object):
    def __enter__(self):
        print('open file')
        return self

    def __exit__(self, type, value, traceback):
        print('close file')

    def do_something(self):
        print('do something')
>>> with FileOpen() as f_obj:
...     f_obj.do_something()
... 
open file
do something
close file

Exceptions

The other point to note, is that exceptions are passed into the __exit__ method as input arguments. This allows you to dictate how your context manager exits in the event of an exception being raised. Heres an example,

class FileOpen(object):
    def __enter__(self):
        print('open file')
        return self
    def __exit__(self, type, value, traceback):
        print('error type:  {0}'.format(type))
        print('error value: {0}'.format(value))
        print('error traceback: {0}'.format(traceback)) 
        print('close file')

    def do_something(self):
        print('do something')
>>> with FileOpen() as fo:
... 12/0
...
open file
error type: <type 'exceptions.ZeroDivisionError'>
error value: integer division or modulo by zero
error traceback: <traceback object at 0x10035c518>
close file
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

contextlib

Python also comes with the contextlib module. This allows us to create a context manager using contextlib’s contextmanager function as a decorator[1].

Here is an example,

from contextlib import contextmanager

@contextmanager
def open_file(name):
    f = open(name, 'w')
    yield f
    f.close()
>>> with open_file('test.txt') as f_obj:
...     f_obj.write('this is a test')

For further information on context manager decorators please see here.

Sources

[1] http://www.blog.pythonlibrary.org/2015/10/20/python-201-an-intro-to-context-managers/

Rick Donato

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial