我有三个模块:
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家伙,因此“随意”导入对我来说似乎很奇怪。无论如何,这里有什么问题?
答案 0 :(得分:3)
导入模块时,导入模块的命名空间。因此,当你有
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 :(得分:2)
请注意堆栈跟踪中除导入之外的其他任何内容都没有错误。我发现这种错误几乎总是与递归循环导入有关。