Python Tutorial

Showing posts with label with. Show all posts
Showing posts with label with. Show all posts

Thursday, December 12, 2013

Context manager API

A context manager is enabled by the with statement, and the API involves two methods. The __enter__() method is run when execution flow enters the code block inside the with. It returns an object to be used within the context. When execution flow leaves the with block, the __exit__() method of the context manager is called to clean up any resources being used.

class Context(object):

    def __init__(self):
        print "Initialize"

    def __enter__(self):
        print "Enter"

    def __exit__(self, exc_type, exc_val, exc_tb):
        print "Exit"


with Context():
    print "Doing something"


Output:
Initialize
Enter
Doing something
Exit

Context manager API

Python file object support the context manager API to make it easy to ensure they are closed after all reading or writing is done

with open('z.txt', 'r') as f:
    data = f.read()
    print data

Output:
File content