Python allows you to import code from ZIP files directly through Zip imports. This interesting built-in feature enables you to zip Python code for distribution purposes. Zip imports also help if you often work with Python code that comes in ZIP files. In either case, learning to create importable ZIP files and to import code from them will be a valuable skill.

Even if your day-to-day workflow doesn’t involve ZIP files containing Python code, you’ll still learn some fun and interesting new skills by exploring Zip imports through this tutorial.

In this tutorial, you’ll learn:

  • What Zip imports are
  • When to use Zip imports in your code
  • How to create importable ZIP files with zipfile
  • How to make your ZIP files available for importing code from them

You’ll also learn how to use the zipimport module to dynamically import code from ZIP files without adding them to Python’s module search path. To do this, you’ll code a minimal plugin system that loads Python code from ZIP files.

To get the most out of this tutorial, you should have previous knowledge of how Python’s import system works. You should also know the basics of manipulating ZIP files with zipfile, working with files, and using the with statement.

Get to Know Python Zip Imports

Since Python 2.3, you can import modules and packages from inside ZIP files. This feature is known as Zip imports and is quite helpful when you need to distribute a complete package as a single file, which is its most common use case.

PEP 273 introduced Zip imports as a built-in feature. The feature was widely accepted as a must-have among the Python community because distributing several separate .py, .pyc, and .pyo files isn’t always appropriate and efficient.

Zip imports can simplify the process of sharing and distributing your code so that your colleagues and end users don’t have to fumble around trying to extract the files into the right location to get the code working.

PEP 302 added a series of import hooks that provides built-in support for Zip imports. If you want to import modules and packages from a ZIP file, then you just need the file to appear in Python’s module search path.

The module search path is a list of directories and ZIP files. It lives in sys.path. Python automatically searches through items in this list when you run an import statement in your code.

In the following sections, you’ll learn how to create ready-to-import ZIP files using different Python tools and techniques. You’ll also learn about a few ways to add those files to your current Python’s module search path. Finally, you’ll dig into zipimport, the module that supports the Zip import feature behind the scenes.

Create Your Own Importable ZIP Files

Zip imports allow you to quickly distribute code that’s organized across several modules and packages as a single file. Python has you covered when it comes to creating importable ZIP files. The zipfile module from the standard library includes a class called ZipFile for manipulating ZIP files. It also includes a more specialized class called PyZipFile, which facilitates the creation of importable ZIP files.

PyZipFile lets you bundle Python code into ZIP files quickly and efficiently. The class inherits from ZipFile, so it shares the same base interface. However, there are two main differences between these classes:

  1. The initializer of PyZipFile takes an optional argument called optimize, which allows you to optimize the Python code by compiling it to bytecode before archiving it.
  2. The PyZipFile class provides a method called .writepy(), which accepts a Python module or package as an argument and adds it to a target ZIP file.

If optimize is -1, its default value, then the input .py files are automatically compiled to .pyc files and then added to the target archive. Why does this happen? Packaging .pyc files rather than the original .py files makes the importing process way more efficient by skipping the compilation step. You’ll learn more about this topic in upcoming sections.

In the following two sections, you’ll get your hands dirty and start creating your own importable ZIP files containing modules and packages.

Bundle Python Modules Into ZIP Files

In this section, you’ll use PyZipFile.writepy() to compile a .py file down to bytecode and add the resulting .pyc file to a ZIP archive. To try .writepy() out, say that you have a module:

"""Print a greeting message."""

def greet(name="World"):
    print(f"Hello, {name}! Welcome to Real Python!")

This module defines a function called greet() that takes name as an argument and prints a friendly greeting message to the screen.

Now say that you want to package this module into a ZIP file that you can import later. To do this, you can run the following code:

当前网页内容, 由 大妈 ZoomQuiet 使用工具: ScrapBook :: Firefox Extension 人工从互联网中收集并分享;
若有不妥, 欢迎评注提醒:


订阅 substack 体验古早写作:

点击注册~> 获得 100$ 体验券: DigitalOcean Referral Badge

关注公众号, 持续获得相关各种嗯哼:


关于 ~ DebugUself with DAMA ;-)
公安备案号: 44049002000656 ...::