With Python with

The with statement is used to wrap the execution of a block with methods defined by a context manager. This allows common try…except…finally usage patterns to be encapsulated for convenient reuse.

The with statement has been around for the quite sometime now, I guess it has been around for about 5 years(since 2.5 python release). And has found its way into many python libraries as well.

So much so that even the file open statement also has a with wrapper. So does that mean?

with open('sample.txt') as f:
    f.read(1)

The above starts by passing the open file handle into f, and within the with nest you could operate on f. And assume that there is an exception inside the nest, the f handle would close safely by the with construct.

Rainbow with Lightening by thinboyfatter on Flickr

So this is how they you need implement you class to be operated with a with.

class  somefunkey:
    def __enter__(self):
        setting things up here
        return self.some_object
    def __exit__(self, exc_type, exc_value, traceback):
        tear it all down :)
        del self.some_object

Now somefunkey could be used alongside with to provide some_object to operate upon in the nest like this.

with somefunkey() as object:
    operate on the object

And notice, since you have deleted the some_object in tear down function, the object is just constrained to be used within the nest. You could read more about Context Managers of with here.

 
0
Kudos
 
0
Kudos

Now read this

Why and how should I blog?

I, Me and Myself # This is a question that I have asked myself over the years that I have been blogging, here, here, here, and other places. The only reason that I was blogging in all those people is to get as many followers as possible,... Continue →