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

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.


The other day, I came across an interesting StackOverflow question where the fellow was trying to figure out how to open a sub-frame only once. Basically he wanted a single instance of the sub-frame (and other sub-frames). After digging around a bit on Google, I found an old thread from the wxPython Google Group that had an interesting approach to doing what was needed.

Basically it required a bit of meta-programming, but it was a fun little exercise that I thought my readers would find interesting. Here’s the code:


I recently completed Episode #10 of the Python 101 Screencast. It’s about the basics of functions. I hope you like it!

I recently came across a StackOverflow question where the fellow was asking how to get wxPython’s RichTextCtrl’s XML data so he could save it to a database. I don’t know much about this control, but after a quick Google search, I found an article from 2008 that gave me the information I needed. I took that example and cut it down to the following example:


Check out my latest video from the Python 101 Screencast. In this episode we learn how to use Python’s file handling capabilities. You will learn how to read, write and append to a file.

I recently recorded the next episode of Python 101. This one is on Exception Handling. I hope you like it:

I finished up another Episode of Python 101. This one is about Python’s comprehension constructs. In this video, I cover list, dict and set comprehensions. I hope you enjoy it:

You can support my Python 101 video project via my IndieGogo crowdfunding campaign, which is ending this week.

I recorded the next episode of my Python 101 screencast today. You can support my crowdfunding campaign here.

The video is about Python’s looping structures. You will also learn how to use the else construct with a loop. Here’s the video:

Next Page »