python-clinic / Doc / library / zipimport.rst

Full commit

:mod:`zipimport` --- Import modules from Zip archives

This module adds the ability to import Python modules (:file:`\*.py`, :file:`\*.py[co]`) and packages from ZIP-format archives. It is usually not needed to use the :mod:`zipimport` module explicitly; it is automatically used by the built-in :keyword:`import` mechanism for :data:`sys.path` items that are paths to ZIP archives.

Typically, :data:`sys.path` is a list of directory names as strings. This module also allows an item of :data:`sys.path` to be a string naming a ZIP file archive. The ZIP archive can contain a subdirectory structure to support package imports, and a path within the archive can be specified to only import from a subdirectory. For example, the path :file:`` would only import from the :file:`lib/` subdirectory within the archive.

Any files may be present in the ZIP archive, but only files :file:`.py` and :file:`.py[co]` are available for import. ZIP import of dynamic modules (:file:`.pyd`, :file:`.so`) is disallowed. Note that if an archive only contains :file:`.py` files, Python will not attempt to modify the archive by adding the corresponding :file:`.pyc` or :file:`.pyo` file, meaning that if a ZIP archive doesn't contain :file:`.pyc` files, importing may be rather slow.

ZIP archives with an archive comment are currently not supported.

This module defines an exception:

zipimporter Objects

:class:`zipimporter` is the class for importing ZIP files.

Create a new zipimporter instance. archivepath must be a path to a ZIP file, or to a specific path within a ZIP file. For example, an archivepath of :file:`foo/` will look for modules in the :file:`lib` directory inside the ZIP file :file:`foo/` (provided that it exists).

:exc:`ZipImportError` is raised if archivepath doesn't point to a valid ZIP archive.

The :attr:`archive` and :attr:`prefix` attributes, when combined with a slash, equal the original archivepath argument given to the :class:`zipimporter` constructor.


Here is an example that imports a module from a ZIP archive - note that the :mod:`zipimport` module is not explicitly used.

$ unzip -l
  Length     Date   Time    Name
 --------    ----   ----    ----
     8467  11-26-02 22:30
 --------                   -------
     8467                   1 file
$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32)
>>> import sys
>>> sys.path.insert(0, '')  # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__