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

Need a Print

This morning, at around 8 am, there was a frantic call from my cousin’s husband asking if I was home, so they could stop over for a print. My cousin and her family were on their way to the US Consulate for a Visa interview, and they... Continue →