Sunday, January 20, 2013

with awesome:

with awesome::
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:

@contextmanager
def chdir(path):
    cwd = os.getcwd()
    os.chdir(path)
    yield
    os.chdir(cwd)

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

with chdir('/path/to/dosomething/in'):
    os.system('doit')

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

@contextmanager
def umask(new_mask):
    cur_mask = os.umask(new_mask)
    yield
    os.umask(cur_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('/'):
     os.system('/your/command')

Code for these examples is available on my GitHub page.

DIGITAL JUICE

No comments:

Post a Comment

Thank's!