Python: Custom WITH statement / Context Manager

The Python WITH statement lets an object do something when it enters the scope and when it exits the scope. You must have seen code like this:

with open(filename) as f: 
    # do something

The file will be closed when it is out of scope no matter how it goes out of scope. This behavior is implemented by a pair of methods, and classes that implement these methods are called context managers. Here is an example:

class Demo:   
    def __init__(self, msg):
        print("creating")
        self.msg = msg
    
    def __enter__(self):
        print("entering")
        return self
    
    def __exit__(self, type, value, traceback):
        print("exiting")
        
    def hello(self):
        print(self.msg)
        
with Demo('hello world!') as d:
    d.hello()

Results:

creating
entering
hello world!
exiting

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s