The Module Search Path

When loading modules, the interpreter searches the list of directories in sys.path.The first entry in sys.path is typically an empty string '', which refers to the current working directory. Other entries in sys.path may consist of directory names, .zip archive files, and .egg files.The order in which entries are listed in sys.path determines the search order used when modules are loaded. To add new entries to the search path, simply add them to this list.

Although the path usually contains directory names, zip archive files containing Python modules can also be added to the search path. This can be a convenient way to package a collection of modules as a single file. For example, suppose you created two modules, and, and placed them in a zip file called The file could be added to the Python search path as follows:

import sys") import foo, bar

Specific locations within the directory structure of a zip file can also be used. In addition, zip files can be mixed with regular pathname components. Here's an example:


In addition to .zip files, you can also add .egg files to the search path. .egg files are packages created by the setuptools library.This is a common format encountered when installing third-party Python libraries and extensions. An .egg file is actually just a .zip file with some extra metadata (e.g., version number, dependencies, etc.) added to it.Thus, you can examine and extract data from an .egg file using standard tools for working with .zip files.

Despite support for zip file imports, there are some restrictions to be aware of. First, it is only possible import .py, .pyw, .pyc, and .pyo files from an archive. Shared libraries and extension modules written in C cannot be loaded directly from archives, although packaging systems such as setuptools are sometimes able to provide a workaround (typically by extracting C extensions to a temporary directory and loading modules from it). Moreover, Python will not create .pyc and .pyo files when .py files are loaded from an archive (described next). Thus, it is important to make sure these files are created in advance and placed in the archive in order to avoid poor performance when loading modules.

Was this article helpful?

0 0

Post a comment