gpt4 book ai didi

python - "import"更喜欢什么 - .pyd (.so) 还是 .py?

转载 作者:行者123 更新时间:2023-12-02 12:00:50 25 4
gpt4 key购买 nike

我在同一目录中有 2 个文件,一个编译后的库文件和源文件:

.
├── a.py
└── a.pyd

它看起来像import a,实际上导入了a.pyd模块。但我找不到任何官方文件来保证这一点。

有人知道不同文件类型的导入顺序吗?

同样的问题也适用于 Unix Python 扩展 (.so)

最佳答案

在典型的 Python 安装中,ExtensionFileLoader类优先于 SourceFileLoader用于 .py 文件。它是处理 .pyd 文件导入的 ExtensionFileLoader,在 Windows 计算机上,您会发现 .pydimportlib.machinery.EXTENSION_SUFFIXES 中注册。 (注意:在 Linux/macOS 上,它将包含 .so)。

因此,在同一目录内发生名称冲突的情况下(这意味着按顺序查看 sys.path 时出现“平局”),a.pyd 文件将采用优先于 a.py 文件。您可以验证在创建空的 a.pyda.py 文件时,语句 import a 尝试加载 DLL(并且失败了,当然)。

要查看 CPython 源代码中的优先级,请查看 here in importlib._bootstrap_external. _get_supported_file_loaders :

def _get_supported_file_loaders():
"""Returns a list of file-based module loaders.
Each item is a tuple (loader, suffixes).
"""
extensions = ExtensionFileLoader, _imp.extension_suffixes()
source = SourceFileLoader, SOURCE_SUFFIXES
bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES
return [extensions, source, bytecode] # <-- extensions before source!

有关文档引用,请参阅 http://www.python.org/doc/essays/packages/

What If I Have a Module and a Package With The Same Name?

You may have a directory (on sys.path) which has both a module spam.py and a subdirectory spam that contains an _init_.py (without the _init_.py, a directory is not recognized as a package). In this case, the subdirectory has precedence, and importing spam will ignore the spam.py file, loading the package spam instead. If you want the module spam.py to have precedence, it must be placed in a directory that comes earlier in sys.path.

(Tip: the search order is determined by the list of suffixes returned by the function imp.get_suffixes(). Usually the suffixes are searched in the following order: ".so", "module.so", ".py", ".pyc". Directories don't explicitly occur in this list, but precede all entries in it.)

本文档没有明确提及“.pyd”,但它在 Windows 中相当于“.so”。我刚刚在 Windows 机器上进行了测试,确实在后缀列表中 '.pyd' 出现在 '.py' 之前。

请注意,上面给出的引用文献非常古老!自从写这篇文章以来,导入系统已经被彻底改造,底层机制已经暴露给用户访问:你可以改变 sys.meta_path例如,注册您自己的加载程序或更改优先级。因此,现在可以自定义“.py”而不是“.pyd”,并且 imp.get_suffixes() 所说的任何内容并不重要(实际上,该功能现已弃用)。当然,默认的 Python 安装不会这样做,并且默认优先级与上面提到的引用保持相同。

关于python - "import"更喜欢什么 - .pyd (.so) 还是 .py?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58686448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com