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. foo.py 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 foo.py is say:

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

If all my classes were in a single Python source file called package.py, this would be the default behavior. Alternatively, I could say from package import * in foo.py, 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 __init__.py 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: ,