Skip to main content
 首页 » 编程设计

python之在 python 包中导入

2024年12月31日9langtianya

我在以下代码中遇到导入错误(导入错误:无法导入名称“ClassB”):

目录结构:

main.py 
test_pkg/ 
    __init__.py 
    a.py 
    b.py 

main.py:

from test_pkg import ClassA, ClassB 

__init__.py:

from .a import ClassA 
from .b import ClassB 

a.py:

from test_pkg import ClassB 
class ClassA: 
    pass 

b.py:

class ClassB: 
    pass 

过去我通过在 a.py 的导入中添加全名来快速“实验”修复它:

from test_pkg.b import ClassB 
class ClassA: 
    pass 

我读过有关进口机械的资料,并根据:

此名称将用于导入搜索的各个阶段,它可能是子模块的点路径,例如foo.bar.baz。在这种情况下,Python 首先尝试导入 foo,然后是 foo.bar,最后是 foo.bar.baz。 link2doc

我原以为它会再次失败,因为它会在 test_pkg 导入期间尝试导入 test_pkg,但它正在运行。我的问题是为什么?

另外还有2个问题:

  1. 跨模块依赖是否是正确的方法?
  2. 是否可以在包 init.py 中导入模块?

我的分析:

根据阅读,我认识到很可能是问题所在,因为关闭

__init__.py: 
from .a import ClassA 
from .b import ClassB 

ClassA 和 ClassB 导入作为 test_pkg 导入的一部分执行,但随后命中 a.py 中的导入语句:

a.py: 
from test_pkg import ClassB 
class ClassA: 
    pass 

它失败了,因为发生了循环依赖。

但是在使用导入时工作:

from test_pkg.b import ClassB 

根据我的理解,它不应该,因为:

This name will be used in various phases of the import search, and it may be the dotted path to a submodule, e.g. foo.bar.baz. In this case, Python first tries to import foo, then foo.bar, and finally foo.bar.baz. If any of the intermediate imports fail, a ModuleNotFoundError is raised.

所以我期待两个导入的行为相同。

看起来完整路径导入没有启动有问题的 test_pkg 导入过程

from test_pkg.b import ClassB 

请您参考如下方法:

您的文件名为 b.py,但您正在尝试import B,而不是import b。

根据您的平台(详见 PEP 235),这可能有效,也可能无效。如果它不起作用,则症状将与您所看到的完全相同:ImportError: cannot import name 'B'。

解决方法是 from test_okg import b。或者,如果您希望将模块命名为 B,请将文件重命名为 B.py。

这实际上与包无关(除了您收到的错误消息是 cannot import name 'B' 而不是 No module named 'B',因为在失败的 from … import 语句中,Python 无法判断您是从包中导入模块失败,还是从模块中导入某个全局名称)。


那么,为什么会这样呢?

from test_pkg.b import B 

I was expecting it will fail again, because it will try to import test_pkg during test_pkg import, but it is working. My question is why?

因为首先导入 test_pkg 不是问题;导入 test_pkg.B 是。您通过导入 test_pkg.b 解决了这个问题。

test_pkg.b在test_pkg/b.py中成功找到。

然后,在该模块中找到 test_pkg.b.B,并将其导入到您的模块中,因为在 b 中当然有一个 class B: 语句。 py.


对于您的后续问题:

is it proper approach to have cross modules dependencies?

只要它们不是循环的,跨模块依赖就没有错,而你的不是。

test_pkg.a 完全可以通过绝对导入导入 test_pkg.b,例如 from test_pkg import b。

但是,通常最好使用相对导入,例如 from 。 import b(除非您需要在 Python 2.x 和 3.x 上工作相同的双版本代码)。 PEP 328解释为什么相对导入通常对包内依赖关系更好(以及为什么它只是“通常”而不是“总是”)。

is it ok to have modules imported in package __init__.py?

是的。事实上,这是一个非常常见的习语,用于多种用途。

例如,参见 asyncio.__init__.py ,它从每个子模块导入所有公共(public)导出并重新导出它们。子模块中有一些很少使用的名称,它们不是以 _ 开头但不包含在 __all__ 中,如果你想使用它们,你需要显式导入子模块。但是您在典型程序中可能需要的所有内容都包含在 __all__ 中并由包重新导出,因此您可以只编写,例如 asyncio.Lock的 asyncio.locks.Lock。