This is one of those days where I had to look up something I knew to make sleep better tonight. Maybe the brain cell that stored this information is acting flaky or I expelled it one night at the bar. In any case it was time to review that tricky __init__.py along with Python modules and packages.
Python allows you to configure several paths that may be searched by Python when it attempts to resolve your modules and packages to load.
A statement like:
from hurley.web.xml import domparser
Will cause Python to search within paths (listed in environment variable PYTHON_PATH, the path which you ran the interpreter from). You can get a list using:
python -c "import sys; print sys.path"
Were not really here to get into how paths are added to Python. On to modules and packages…
Suppose our python path specified /home/hurley/ in its results. Then in order to provide the domparser we specified above we would need a path and file as such: /home/hurley/web/xml.py
Inside xml.py, we are expecting a class named domparser. Actually it doesn’t have to be a formal class. Instead domparser could be a function or variable as well.
Modules are files similar to xml.py, and reside with sub-directories. Packages reside in sub-directories or are sub-directories themselves and create a package, collection of grouped modules. Simply adding a file __init__.py (note two preceding and appending underscores around init) tells Python that the subdirectory is a Package, not just and ordinary directory.
More about __init__.py
This special file can also include code to specify exactly which files (or Modules) should be considered part of the package if you wanted.
If you used:
from hurley.web import *
would instruct the import of all accessible objects. (This is considered a dirty/bad practice…but I’m not here to judge anyone, including myself!) You can limit the inclusion by adding a short piece of code in __init__.py like this:
__all__ = ['writeXmlfunc', 'loadXmlfunc', 'varABC', 'domparser']
Thats all for now…