DEV Community

Rowida
Rowida

Posted on • Updated on

Context Managers with `with` statement in python

What is a Context Manager?

It's an object, that is notified when a context or a block of code starts and ends, of a class that implements the 2 magic methods __enter__ and __exit__ and any other methods if needed.

For example: when a context manager ends, the object file is closed.

with open('test_ch30.txt' , 'w+') as file:
    file.write('Blew the lid of ur life')

 # the open file has automatically been closed 
Enter fullscreen mode Exit fullscreen mode

Context manager is commonly used on reading and writing files to assist in conserving system memory and improve resource management by ensuring that each process holds its resources while executing.

Opening a file using with statement ensures that File descriptor are closed automatically.

How with statment implements a context manager?

1- When an object is called with a with statement, the
interpreter invokes the __enter__ method ,which is used to
call and perform the setup code required and needed for the
process to be executed, before the with statement.

2- When the with statements ends, the interpreter invokes the __exit__ method .

Illustration :

alt text

What's required to implement a contect manager class?

class ContextManager(object):
    """docstring for ContextManager"""
    def __init__(self):
        pass

    def __enter__(self):
        print("__enter__()")
        # optional return an obj
        return "an instance"

    def __exit__(self , exc_type , exc_val , traceback):
        print("__exit__ with " , exc_val if exc_val else ' nope')


with ContextManager() as e:
    print("is a " , e)

Enter fullscreen mode Exit fullscreen mode

Multiple context managers


with open('test_ch30.txt') as input_file, open('test_ch77.txt', 'w') as output_file:
    # do something with both files.
    # e.g. copy the contents of input_file into output_file
    for line in input_file:
        output_file.write(line + '\n')

# It has the same effect as nesting context managers:
with open('test_ch30.txt') as input_file:
    with open('test_ch77.txt', 'w') as output_file:
        for line in input_file:
            output_file.write(line + '\n')

Enter fullscreen mode Exit fullscreen mode

Manage Resources

class File():
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
    def __enter__(self):
        self.open_file = open(self.filename, self.mode)
        return self.open_file
    def __exit__(self, *args):
        self.open_file.close()


for _ in range(10000):
    with File('test_ch30.txt', 'w') as f:
        f.write('foo')

Enter fullscreen mode Exit fullscreen mode

ManageFile class follow.

ManageFile class follow/adhere the context manager protocol and support the with statement Code link

Top comments (0)