Python Tutorial

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

0 comments:

Post a Comment