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.

Many programming languages have the concept of the lambda function. In Python, the lambda is an anonymous function or unbound function. The syntax for them looks a bit odd, but it’s actually just taking a simple function and turning it into a one-liner. Let’s look at a regular simple function to start off:

def doubler(x):
    return x*2

All this function does is take an integer and double it. Technically, it will also double other things too since there’s no type checking but that is its intent Now let’s turn it into a lambda function!


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.


This week we welcome Carol Willing (@WillingCarol) as our PyDev of the Week. Let’s spend some time learning more about our fellow Pythonista!


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

I love Python! The language, the libraries, and the community. I’ve met so many talented, creative Pythonistas in my Python journey, and you inspire me.

I work as an independent consultant in San Diego, spend time teaching and creating as a Geek in Residence at Fab Lab San Diego, and contribute to open source software and hardware as a developer, writer, and teacher. My days are filled with writing lots of code, taking apart vintage electronics, and encouraging others to fabricate their ideas with code, Raspberry Pis, Arduinos, and wearable electronics. The Fab Lab is a special place, and I’ve been nurturing a Gentle Code Garden there. The Gentle Code Garden is a cross between a Python sprint, an inclusive hackerspace, and a community garden. 

My hobbies, such as restoring musical instruments, playing guitar/ukulele, tidepooling, and succulent gardening, are strongly influenced by my education and interests. My formal education includes an Electrical Engineering degree from Duke and an MS in Management from MIT with a focus on econometrics and technical innovation. I’m a voracious nonfiction reader, music lover, and a friendly introvert who enjoys hearing the creative thoughts and ideas of others.


Have you ever wondered how to process command line arguments in Python? Yeah, there’s a module for that. It’s called argparse, which is a replacement for optparse. In this article, we’ll be taking a whirlwind tour of this helpful module. Let’s start with something simple!

Getting Started

I have always found the simplest way to explain a coding concept is to show some code. So that’s what we’re going to do. Here’s a super simple example that doesn’t do much of anything:

>>> import argparse
>>> parser = argparse.ArgumentParser(
...         description="A simple argument parser",
...         epilog="This is where you might put example usage"
...     )
>>> parser.print_help()
usage: [-h]
A simple argument parser
optional arguments:
  -h, --help  show this help message and exit
This is where you might put example usage

Here we just import argparse and give it a description and set up a usage section. The idea here is that when you ask the program you are creating for help, it will tell you how to use it. In this case, it prints out a simple description, the default optional arguments (“-h” in this case) and example usage.


This week we welcome Michael Fogleman as our PyDev of the Week! Mr. Foglebird has been helping out Python programmers prodigiously on StackOverflow for quite some time. I know I’ve appreciated some of his answers when I’ve gone to look for help. He has a large list of personal programming projects on his website that are well worth a look through. Let’s take some time to learn some more about him.


This week we welcome Tracy Osborn as our PyDev of the Week. She is active in the Django portion of the Python universe. Let’s spend some time getting to know her.



Next Page »