Python Packages - groupings of modules. An introduction
Archive - Originally posted on "The Horse's Mouth" - 2011-10-11 21:23:06 - Graham Ellis
As your Python code grows in volume, you'll want to arrange it into subdirectories, with a mirroring mechanism within the language to let you have the extra heirarcy as you load the code from the subdirectory. And you're looking at python packages.
They work as follows:
a) You put the modules that you want in your package into your subdirectory
b) You create an (initially) empty file called __init__.py in the subdirectory (to tell Python it's a package)
c) You use a "." notation to refer to the module within the package.
Here's the change in my calling code when I have moved a module into a package:
There is a much more complex and fully featured example in the Python documentation at http://docs.python.org/tutorial/modules.html - that tells you how to reference across between one module and another within packages, and how to control "*" imports with a list called __all__ within the __init__.py file (which can also include initialisation code).