Entries tagged with “Python”.

Last month I wrote about context managers and a company called Webucator asked me for my permission to turn the article into a screencast. It ended up looking pretty good. Check it out below:

Webucator has other Python related training too. I don’t know much about them, but if this video is any indication, I think they would be worth checking out.

This week we welcome Arun Ravindran (@arocks) as our PyDev of the Week! Arun has a fun Python blog that is worth checking out. He is also the author of Django Design Patterns and Best Practices. Let’s spend some time getting to know Arun.



This week we welcome Amit Saha as our PyDev of the Week! Amit is the author of Doing Math with Python and Write Your First Program. Let’s take some time to get to know Amit better!


This week we welcome Brian Schrader (@sonicrocketman) as our PyDev of the Week. Brian blogs about Python and various other subjects of interest. You can get a taste of what open source projects he contributes to on his Github account. Let’s spend some time getting to know Brian better.



This week we welcome Craig Bruce (@craigbruce) as our PyDev of the Week. Let’s see what he had to say!

Can you tell us a little about yourself (hobbies, education, etc):

My background is in computational chemistry and cheminformatics. What that really means is that I’m trained to work in the small, and mainly unheard, field of early stage drug discovery, where computers are used to aid guide drug design. This work is often ten years before a drug makes it to market.

In recent years Python has become my programming language of choice from scripting to web stacks. The scientific Python stack has grown tremendously in recent years making it easier to focus on your specific research. I have little in the way of formal IT/CS education, but I’ve picked up a lot over through my education and previous roles both in programming and system administration.

My hobbies include hiking, skiing and walking my dog, I live in New Mexico where we enjoy the amazing outdoor.


This week we welcome Jaime Fernández del Río as our PyDev of the Week. He is a core developer of NumPy. Let’s spend some time getting to know him a bit better!

Can you tell us a little about yourself (hobbies, education, etc):

I’m originally from Madrid (Spain), where I earned my Mechanical Engineering degree. I worked in Germany for a few months, but eventually moved back to Spain, to Barcelona, where I met my wife Eva, and where our two children, Lucas and Gabriela, were born. For the past four years we have been giving the American dream a try in San Diego, courtesy of my employer for the past 15 years, Hewlett-Packard.

I used to be very active, having played rugby for several years at the club level, and trained and raced for long distance triathlon for a few more. In the crazy department, I was an avid barefoot runner, and used to commute to work on a fixed gear bicycle. These days, between work, family, and my involvement in open source, I can’t seem to find the time or motivation to exercise. But I am still delusional about one day completing a no wetsuit, fixed gear, barefoot Ironman.


The wxPython toolkit added context managers to its code base a few years ago, but for some reason you don’t see very many examples of their use. In this article, we’ll look at three examples of context managers in wxPython. A wxPython user was the first person to suggest using context managers in wxPython on the wxPython mailing list. We’ll start off by rolling our own context manager and then look at a couple of examples of built-in context managers in wxPython.


Python came out with a special new keyword several years ago in Python 2.5 that is known as the “with statement”. This new keyword allows a developer to create context managers. But wait! What’s a context manager? They are handy constructs that allow you to set something up and tear something down automatically. For example, you might want to open a file, write a bunch of stuff to it and then close it. This is probably the classic example of a context manager:

with open(path, 'w') as f_obj:

Back in Python 2.4, you would have to do it the old fashioned way:

f_obj = open(path, 'w')

The way this works under the covers is by using some of Python’s magic methods: __enter__ and __exit__. Let’s try creating our own context manager to demonstrate how this all works!

Creating a Context Manager class

Rather than rewrite Python’s open method here, we’ll create a context manager that can create a SQLite database connection and close it when it’s done. Here’s a simple example:

import sqlite3
class DataConn:
    def __init__(self, db_name):
        self.db_name = db_name
    def __enter__(self):
        Open the database connection
        self.conn = sqlite3.connect(self.db_name)
        return self.conn
    def __exit__(self, exc_type, exc_val, exc_tb):
        Close the connection
if __name__ == '__main__':
    db = '/home/mdriscoll/test.db'
    with DataConn(db) as conn:
        cursor = conn.cursor()

In the code above, we created a class that takes a path to a SQLite database file. The __enter__ method executes automatically where it creates and returns the database connection object. Now that we have that, we can create a cursor and write to the database or query it. When we exit the with statement, it causes the __exit__ method to execute and that closes the connection.

Let’s try creating a context manager using another method.

Creating a Context Manager using contextlib

Python 2.5 not only added the with statement, but it also added the contextlib module. This allows us to create a context manager using contextlib’s contextmanager function as a decorator. Let’s try creating a context manager that opens and closes a file after all:

from contextlib import contextmanager
def file_open(path):
        f_obj = open(path, 'w')
        yield f_obj
    except OSError:
        print "We had an error!"
        print 'Closing file'
if __name__ == '__main__':
    with file_open('/home/mdriscoll/test.txt') as fobj:
        fobj.write('Testing context managers')

Here we just import contextmanager from contextlib and decorate our file_open function with it. This allows us to call file_open using Python’s with statement. In our function, we open the file and then yield it out so the calling function can use it. Once the with statement ends, control returns back to the file_open function and it continues with the code following the yield statement. That causes the finally statement to execute, which closes the file. If we happen to have an OSError while working with the file, it gets caught and finally statement still closes the file handler.

Wrapping Up

Context managers are a lot of fun and come in handy all the time. I use them in my automated tests all the time for opening and closing dialogs, for example. Now you should be able to use some of Python’s built-in tools to create your own context managers. Have fun and happy coding!

Related Reading

This week we welcome Ryan Mitchell (@Kludgist) as our PyDev of the Week. Ryan is the author of Web Scraping with Python and Instant Web Scraping with Java. Let’s spend some time getting to know Ryan better.


Packt Publishing recently sent me a copy of Mastering Python High Performance by Fernando Doglio. They also had me be a technical reviewer of the book before its publication. Anyway let’s do a quick review and if you think it sounds interesting, you can check out my full review too!

Quick Review

  • Why I picked it up: I got it for free, but I did find the title intriguing.
  • Why I finished it: As a technical reviewer of the book, I had to read it all the way through. However, it has a lot of interesting concepts and it was short.
  • I’d give it to: Someone who needs to learn about how to increase their Python code’s efficiency.