Archive of July 2012

Tue 24 Jul

Creating and importing custom Python packages

I'm building a custom Python package for a project I'm working on, and it took me more time than should have been needed to figure out how to achieve the import behavior I wanted for that package. The directory structure looks like this:


Each of the files in the package defines some classes; for now, we can assume they each have just one eponymous class. is the driver script that the user actually runs, which mainly just accepts command line arguments and imports the package.

What I'd like to be able to do in is say:

import package
b = package.Bar("asdf")

If all my classes were in a single Python source file called, this would be the default behavior. Alternatively, I could say from package import * in, but that would import my modules directly and frankly I think it looks ugly.

The way to achieve the desired behavior is to perform the imports of each module in the package in the file, like so:

from Bar import *
from Baz import *
from Qux import *

Now, when we import the package, all the associated modules come with it.

I found this post very helpful in understanding how modules work, as well as the official documentation.

· Tags: ,