简体   繁体   English

Python 如何处理子包?

[英]How does Python handle subpackages?

Say Ansible was installed by means of "pip install ansible".说 Ansible 是通过“pip install ansible”安装的。 Right after the install the following import statement succeeds:安装后立即执行以下导入语句:

from ansible.module_utils.basic import AnsibleModule

Now, a local package named "ansible.module_utils.custom" is created.现在,创建了一个名为“ansible.module_utils.custom”的本地包。 The directory structure:目录结构:

 ansible/
   __init__.py
   module_utils/
     __init__.py
     custom/
       __init__.py
       utils.py

As soon as this is put in place the aforementioned import statement fails.一旦实施,上述导入语句就会失败。 Claiming "basic" is undefined.声称“基本”是不确定的。 The local package does indeed not declare a "basic" subpackage.本地包确实没有声明“基本”子包。 Only the installed Ansible library does.只有安装的 Ansible 库可以。 It seems Python limited its search to the local package only.似乎 Python 仅限于搜索本地包。

I was under the impression Python would consider the complete system path before giving up on finding code.我的印象是 Python 在放弃查找代码之前会考虑完整的系统路径。 That it would backtrack out of the local package and finally hit the installed Ansible library.它会从本地包中回溯并最终命中已安装的 Ansible 库。

Is this an incorrect assumption ?这是一个不正确的假设吗? If so, is it possible at all to make the local package to coexist with the installed package ?如果是这样,是否有可能使本地包与已安装的包共存?

How Import works导入的工作原理

import abc

The first thing Python will do is look up the name abc in sys.modules. Python 要做的第一件事是在 sys.modules 中查找名称 abc。 This is a cache of all modules that have been previously imported.这是之前导入的所有模块的缓存。

If the name isn't found in the module cache, Python will proceed to search through a list of built-in modules.如果在模块缓存中找不到该名称,Python 将继续搜索内置模块列表。 These are modules that come pre-installed with Python and can be found in the Python Standard Library.这些是 Python 预装的模块,可以在 Python 标准库中找到。 If the name still isn't found in the built-in modules, Python then searches for it in a list of directories defined by sys.path.如果在内置模块中仍未找到该名称,Python 将在 sys.path 定义的目录列表中搜索它。 This list usually includes the current directory, which is searched first.该列表通常包括首先搜索的当前目录。

When Python finds the module, it binds it to a name in the local scope.当 Python 找到该模块时,它会将其绑定到本地范围内的一个名称。 This means that abc is now defined and can be used in the current file without throwing a NameError.这意味着现在定义了 abc 并且可以在当前文件中使用而不会抛出 NameError。

If the name is never found, you'll get a ModuleNotFoundError.如果从未找到该名称,您将收到 ModuleNotFoundError。 You can find out more about imports in the Python documentation here !您可以在此处的 Python 文档中找到有关导入的更多信息!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM