2011-04-16 63 views
0

我有三個模塊:爲什麼Python導入不工作?

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

'jpa_export_fragments'和'jpa_export_helpers'是你的嗎?畢竟他們正在造成錯誤。 'plugin_grt'不是問題。 – delnan 2011-04-16 12:49:22

+0

注意到plugins_grt和fragments的輸入是什麼,按什麼順序會使問題(和問題)更加清晰。 – msw 2011-04-16 13:06:46

回答

2

請注意堆棧跟蹤中除導入之外沒有任何錯誤。我發現那種錯誤幾乎總是與 遞歸 循環導入有關。

3

當您導入到模塊中時,您將導入模塊的名稱空間。因此,當你在plugin_jrt_py

from jpa_export_helpers import SourceFile 

你實際上已經創建了一個名字plugin_jrt_py.SourceFile。在命名空間解析之後,在plug_in_jrt.py之內,該名稱可以縮短爲SourceFile,但僅在plug_in_jrt之內。

因爲導入有副作用,所以import語句很小心,不要導入模塊兩次。

你沒有指定一個調用序列,但我懷疑fragments.py是由plugin_jrt.py導入的,所以這個名字在沒有資格的情況下是不可訪問的。

儘量放棄from子句和錯誤將變得更加明顯。