with awesome:

Sat, 19 Jan 2013 19:38:43 +0000

Update: This article has some errors, that are correct in a new article.

I'm only like 8 years late to the party on this one, but I've got to say Python's with statement is pretty awesome. Although I've used the functionality off-and-on I'd mostly avoided writing my own context managers as I thought it required classes with magic __enter__ and __exit__ methods. And besides, my other main language is C, so you know, I'm used to releasing resources when I need to.

Anyway, I finally decided that I should actually learn how to make a context manager, and it turns out to be super easy thanks to Python yield statement. So, some truly simple examples that will hopefully convince you to have a go at make your own context managers.

First up, a simple chdir context manager:

def chdir(path):
    cwd = os.getcwd()

If you are doing a lot of shell-style programming in Python this comes in handy. For example:

with chdir('/path/to/dosomething/in'):

A lot simpler than manually having to save and restore directories in your script. Along the same lines a similar approach for umask:

def umask(new_mask):
    cur_mask = os.umask(new_mask)

Again, this avoids having to do lots of saving and restoring yourself. And, the nice thing is that you can easily use these together:

with umask(0o002), chdir('/'):

Code for these examples is available on my GitHub page.

blog comments powered by Disqus