开发者

Why isn't this Python import working?

开发者 https://www.devze.com 2023-02-25 18:57 出处:网络
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, In

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消