为什么在 Python 中不允许从 ZIP 文件导入“*.so”文件?

Why is the import of `*.so` files from ZIP files disallowed in Python?

为什么 Python 中不允许从 ZIP 文件导入 *.so 文件?

文档(https://docs.python.org/2/library/zipimport.html)写的很清楚:

Any files may be present in the ZIP archive, but only files .py and .py[co] are available for import. ZIP import of dynamic modules (.pyd, .so) is disallowed.

但是文档没有说明这种奇怪限制的任何原因。是因为 Python 通常不鼓励从 ZIP 文件导入?还是出于安全原因?如果有,是哪些?有官方说法吗?

来自 PEP 273, Subdirectory Equivalence:

You can't satisfy dynamic modules from a zip file. Dynamic modules have extensions like .dll, .pyd, and .so. They are operating system dependent, and probably can't be loaded except from a file. It might be possible to extract the dynamic module from the zip file, write it to a plain file and load it. But that would mean creating temporary files, and dealing with all the dynload_*.c, and that's probably not a good idea.

我的解释是,做出此决定是为了避免让解释器提取动态模块并将其保存到磁盘,因为 OS 的动态库工具不允许从 zip 文件中加载(参见 Windows' LoadLibraryA and Linux's dlopen)。

虽然看起来这在技术上并非不可能,但实现此功能的工作可能不值得的一个原因是这些库的平台依赖性。 .zip 包含随依赖它的代码一起分发的动态模块,如果它是从 64 位环境创建的,则可能无法在 32 位环境中工作,并且在 Linux 如果它是在 Windows 中创建的。禁止 .zip 中的动态模块可能是一个有意识的决定,以确保包含 Python 模块的 .zip 可以跨平台工作。