为什么这个Python导入不工作?

0 投票
2 回答
686 浏览
提问于 2025-04-16 15:52

我有三个模块:

plugin_grt.py

fragments.py

helpers.py

在plugin_grt.py的最上面,我写了:

from jpa_export_helpers import SourceFile, Mysql, Conv, Columns, Column, Table, ForeignKey, Index, Catalog, Inheritance

这样做是有效的,我可以毫无问题地使用Table.whateverMethod(...)。但是,当我在fragments.py模块的顶部添加相同的导入时,我遇到了:

Traceback (most recent call last):

  File "C:\Users\Kawu\AppData\Roaming\MySQL\Workbench\modules\jpa_export_plugin_grt.py", line 53, in <module>
    from jpa_export_helpers import SourceFile, Mysql, Conv, Columns, Column, Table, ForeignKey, Index, Catalog, Inheritance

  File "C:\Users\Kawu\AppData\Roaming\MySQL\Workbench\modules\jpa_export_helpers.py", line 2, in <module>
    from jpa_export_fragments import Type, EnumValue

  File "C:\Users\Kawu\AppData\Roaming\MySQL\Workbench\modules\jpa_export_fragments.py", line 2, in <module>
    from jpa_export_helpers import SourceFile, Mysql, Conv, Columns, Column, Table, ForeignKey, Index, Catalog, Inheritance

ImportError: cannot import name SourceFile

为什么这样不行呢?唯一的解决办法是直接在需要的地方导入这些类,但我不太喜欢这样做(至少现在不喜欢):

def getPrimaryKeyColumns(self):
    from jpa_export_helpers import Columns
    return Columns.getPrimaryKeyColumns(self.table.columns)

顺便提一下,我最开始是学Java的,所以随意导入对我来说有点奇怪。那么,这里到底是什么问题呢?

2 个回答

2
 from jpa_export_helpers import SourceFile

当你把一个模块导入到另一个模块时,实际上是把它放进了一个叫做命名空间的地方。举个例子,当你在 plugin_jrt_py 中导入某个东西时,你实际上创建了一个名字 plugin_jrt_py.SourceFile。在 plug_in_jrt.py 这个文件里,你可以把这个名字简化成 SourceFile,但这只在 plug_in_jrt 这个模块里有效。

因为导入操作会有一些副作用,所以 import 这个语句会小心翼翼地避免重复导入同一个模块。

你并不需要指定调用的顺序,但我猜 fragments.py 是被 plugin_jrt.py 导入的,所以在没有特别说明的情况下,你是无法直接使用这个名字的。

试着去掉 from 的部分,你会更清楚地看到错误在哪里。

1

注意到在错误信息中,除了导入相关的内容外,没有其他错误。我发现这种错误几乎总是和循环导入有关。

撰写回答