无法导入命名空间包 "c4d" 但任何其他名称都可以

Can't import namespace package "c4d" but any other name for it works

我自己建立了一个 Python 库的集合,这些库是我在 nr 命名空间下收集的。现在对于一个叫C4D的应用程序中的Python插件,我想使用nr.c4d模块,但是无法导入。奇怪的是,如果我将它重命名为其他名称(例如 nr.c4dlib),它会起作用!

+ nr.c4d\
  + nr\
    * __init__.py  # < pkgutil.extend_path() in here
    + c4d\
      * __init__.py
      * gui.py
      * ...

这是每个命名空间中的代码 __init__.py

# This is a namespace package.
try:
  import pkg_resources
  pkg_resources.declare_namespace(__name__)
except ImportError:
  import pkgutil
  __path__ = pkgutil.extend_path(__path__, __name__)

nr.__path__ 列表似乎也不错。

['C:\maxon\Cinema 4D R16 Dev\plugins\procedural\python\nr',
 'C:\maxon\Cinema 4D R16 Dev\plugins\cloudui_frontend_r16\devel\nr.strex\nr',
 'C:\maxon\Cinema 4D R16 Dev\plugins\cloudui_frontend_r16\devel\nr.concurrency\nr',
 'C:\maxon\Cinema 4D R16 Dev\plugins\cloudui_frontend_r16\devel\nr.cli\nr',
 'C:\maxon\Cinema 4D R16 Dev\plugins\cloudui_frontend_r16\devel\nr.c4d\nr']

但我明白了

Traceback (most recent call last):
  File "'cloudui_frontend.pyp'", line 176, in <module>
ImportError: No module named c4d

环境中有一个名为 c4d 的内置模块可能是相关的。这个错误的根源是什么?如何解决?


Update 问题似乎来自另一个名称空间模块 nr.procedural。它在文件顶部执行 import c4d。如果该行被注释掉,则导入 nr.c4d 有效!另外,我可以添加 from __future__ import absolute_import.

而不是注释掉该行

相对导入导致在 nr.__path__ 第二次扩展之前,在 sys.modules 中为 nr.c4d 创建了一个 None 条目。这是我在 localimport 存储库中打开的问题:

Scenario: nr.procedural does import c4d. If nr.c4d does not exist, the module will be added as a None-entry to sys.modules. If then _localimport is used to import nr.c4d, the module will not be found as the module cache says that the module does not exist (by the None-entry).

Solution: _localimport must delete None-entries for namespace packages on __enter__().

fix相对容易。

我需要将 from __future__ import absolute_import 添加到 import c4d 的所有 nr. 子包中。