- a developer's blog

PythonPath for Modules & Packages – Import Error: No module named “…”

Python offers Modules & Packages(directory of modules) for using third-party codes in our program without having to reinvent the wheel. However, when i started with python -I had a hard time figuring out how to import third-party modules & packages into my program.

Here’s a gist of what I finally learnt:

Know the Python Path

Knowing about the PYTHONPATH is key to installing and importing third-party packages. When an import command is passed, python looks for the module/package in a list of places. The default path(s) where python would search for modules can be found out by:

import sys
print sys.path

For my computer it gives me the the following paths:

[”, ‘C:\\Python27\\Lib\\idlelib’, ‘C:\\Windows\\system32\\’, ‘C:\\Python27\\DLLs’, ‘C:\\Python27\\lib’, ‘C:\\Python27\\lib\\plat-win’, ‘C:\\Python27\\lib\\lib-tk’, ‘C:\\Python27’, ‘C:\\Python27\\lib\\site-packages’]

Starters would do good to install or add modules in one of these paths. If you get this wrong, you will get an error like: ImportError: No module named “foo” . By convention, all third-party packages go into Pythonfolder/Lib/site-packages.

Importing Module or Importing packages ?

When you add a third-party module to your python library, remember that simply dumping a folder with bunch of .py files will not make it a package. When you use the import command, python does not look inside folders, even if the folders are located in the PYTHONPATH. However, if a folder in the PythonPath has a file called, Python jumps inside it and treats the complete folder as a package.

Changing the Pythonpath

If you want to add packages in any other directory (other than the python paths listed above) – you will have to first export the python path in your code with:

 PYTHONPATH=$PYTHONPATH:C/Your new path/yournewmodulefolder

Virtual Environment Builder

Suppose you build several applications in your Python environment where one of your application requires version 1 of PackageX, while another application of yours requires version 2 of PackageX.

If you try placing both these version in the same folder (say site-package), you are in for some trouble. To avoid any such interference, you can have separate Virtual environment for each of your applications using Virtual Python Environment builder.