Python Modules and Packages

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 along with Python modules and packages.

Python Path:
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/

Inside, 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, 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 (note two preceding and appending underscores around init) tells Python that the subdirectory is a Package, not just and ordinary directory.

More about
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 like this:

__all__ = ['writeXmlfunc', 'loadXmlfunc', 'varABC', 'domparser']

Thats all for now…


4 responses to “Python Modules and Packages

  1. Short yet very precise explanation of concepts.
    Really very helpful one..!!!

  2. Yeah, thanks, thumbs up 🙂

  3. Very nice explanation

  4. Thanks, I was looking for a better explanation, I find the official documentation difficult to read, especially since English is not my native language.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s