I have three modules:
plugin_grt.py
fragments.py
helpers.py
Right at the top of plugin_grt.py I have
from jpa_export_helpers import SourceFile, Mysql, Conv, Columns, Column, Table, ForeignKey, Index, Catalog, Inheritance
which works, that is I can use Table.whateverMethod(...) without problems. Now when I add the same import to the top of the fragments.py module I get:
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 <modul开发者_开发技巧e>
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
Why isn't this working? The only workaround is to import the classes right where they're needed, but it's not something I like (at least for now):
def getPrimaryKeyColumns(self):
from jpa_export_helpers import Columns
return Columns.getPrimaryKeyColumns(self.table.columns)
Note, I'm originally a Java guy so importing "at will" seems strange to me. Anyway, what's the problem here?
When you import into a module, you import into the module's namespace. Thus when you have
from jpa_export_helpers import SourceFile
in plugin_jrt_py
you have actually created a name plugin_jrt_py.SourceFile
. Following namespace resolution, within plug_in_jrt.py
that name can be shortened to SourceFile
but only within plug_in_jrt
.
Because an import has side effects, the import
statement is careful not to import a module twice.
You don't specify a calling sequence, but I suspect that fragments.py
is imported by plugin_jrt.py
and so the name is not accessible without qualification.
Try dropping the from
clauses and the error will become more apparent.
Note how there is no error in the stacktrace related to anything other than importing. I found that sort of error almost always is related to recursive circular imports.
精彩评论