Python modules and packages

“In the summertime, when the weather is hot…”

It’s time to write a note about modules and packages in Python.

A module is a python file. A package is a folder/directory on disk. Simple right?

Modules

To import a module from another module, you use import. This command will import the module from either:

  • The current directory
  • Somewhere in the existing PYTHONPATH
  • You modify PYTHONPATH to include the folder where it is located

You can either set PYTHONPATH before executing the interpreter, or you use sys.path.append()

Examples

Assume the following:

  • We create a package MySuperTools with 2 modules.
  • A main application with 2 modules, using the MySuperTools package

To create your own package:

  • Create a directory with the name of your package: mkdir MySuperTools
  • Add the PARENT directory to the path
  • import the package

Example

  • current directory is /home/peter/dev
  • create a subdirectory MySuperTools: mkdir /home/peter/dev/MySuperTools
  • create a file __init__.py to mark it as a package
  • create your modules in this directory
  • Now add /home/peter/dev to your PYTHONPATH, either by modifying the PYTHONPATH environment variable, or by calling sys.path.insert/append inside your program before importing the package

Things to look out for

If you import a single module (a file) it can be anywhere in the PYTHONPATH. If you import a package (a directory with an __init__.py file) then the PACKAGE/DIRECTORY must be in the PYTHONPATH.

Specifically, your PYTHONPATH should NOT specify the directory itself, but the place where the directory is located.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.