Python Packaging

Let’s talk about python packaging as I find it valuable to share with people who are beginners to python.

Let’s imagine if you have a few python scripts which are saved in the following file directory in your computer.

c:/myPythonScript/folderX/
__init__.py
folderY/
__init__.py
scriptY1.py
scriptY2.py
folderZ/
__init__.py
scriptZ1.py
scriptZ2.py
folderYY/
__init__.py
scriptYY1.py
scriptYY2.py

With the python programs stored in a file directory, you will have to know when and how to use
import, from … import
import sys
sys.path.append("c:/myPythonScript")
import folderX

By doing so, the __init__.py in folderX will be loaded.
It will be easier for python to understand the filename convention on the various computer system if we add __all__ in the __init__.py such as below:
# c:/myPythonScript/folderX/folderY/__init__.py
__all__ = [ "scriptY1", "scriptY2", ... ]

With the code above, we can easily use
from folderY import *
without having any problem.

Alternatively you can add the following lines of code into __init__.py in folderY
import scriptY1, scriptY2
so that you can have all the scripts (scriptY1 and scriptY2) loaded with just a
import folderY

If you need to import modules from sibling sub package, you can do the following:
import string
base_package = string.join(string.split(__name__, '.')[:-2], '.')
exec "from %s.folderYY import scriptYY1" %base_package

Interesting python article which can help you package your modules into ZIP using PyZIP.
http://bugs.python.org/msg22134 (bug solved, so you do not have to worry)