On this page
  1. zipimport
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Reading Data Files Bundled Inside a Zip Archive
  7. Gotchas & Boundaries
  8. Classes & Objects

zipimport

Prev: zipfile | Up: stdlib_module | Next: zlib
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — zipimport
Tags: #public #python3 #stdlib


Import

import zipimport

Overview

Import hook (zipimporter) enabling Python to import .py and .pyc modules directly from .zip archives on sys.path (the mechanism behind zipapp .pyz bundles and wheel/egg imports). Reach for zipimport when loading plugins or self-contained Python bundles directly from a zip archive without extracting them to disk.

Quick Start

from pathlib import Path
import tempfile
import zipfile
import zipimport

with tempfile.TemporaryDirectory() as tmp:
    archive = Path(tmp) / "bundle.zip"
    with zipfile.ZipFile(archive, "w") as zf:
        zf.writestr("greeter.py", "def hi(name): return f'hello {name}'\n")

    importer = zipimport.zipimporter(str(archive))
    mod = importer.load_module("greeter")
    assert mod.hi("world") == "hello world"

Implementation Walkthrough

1. Reading Data Files Bundled Inside a Zip Archive

zipimporter.get_data(pathname) reads non-Python assets stored alongside modules inside the archive:

from pathlib import Path
import tempfile
import zipfile
import zipimport

with tempfile.TemporaryDirectory() as tmp:
    archive = Path(tmp) / "assets.zip"
    with zipfile.ZipFile(archive, "w") as zf:
        zf.writestr("pkg/__init__.py", "")
        zf.writestr("pkg/data.txt", "payload")

    importer = zipimport.zipimporter(str(archive))
    raw = importer.get_data(str(archive / "pkg" / "data.txt"))
    assert raw == b"payload"

Gotchas & Boundaries

Classes & Objects

Linked from

Related notes