[英]Python modules (partially) importing from each other
我將一個大型項目(無論如何對我來說!)分解為2或3個模塊,包括帶有頂層菜單等的“主”模塊。它將針對不同方面導入兩個或三個“子模塊”的應用程序。 但是,這些模塊將需要從主模塊進行各種設置等。 是的,它們可以作為參數傳遞,但是其中有很多,它們很容易更改。 不同的模塊將需要不同的設置子集。
我希望能夠使下級模塊根據需要簡單地“返回”其設置(按原樣在各個模塊之間進行全局排序)。
這是我的意思的老鼠示例:
測試1:
# dummy version of main / sub modules with mutual importing
# this is the 'main module'
# in this trivial example, it would be easy to make mode an argument of the function
# but as an alternatiove can test2 'reach back' to test1?
from test2 import taskA
mode = 1
ans = taskA()
print(ans)
測試2:
# dummy version of main / sub modules with mutual importing
# this is the 'sub module' that executes taskA
from test1 import mode
def taskA():
print('taska, mode = {0}'.format(mode))
return 'Hello World!'
mode = 0
print('test2 initialised')
結果是
Traceback (most recent call last):
File "C:\Python33\MyScripts\test1.py", line 6, in <module>
from test2 import taskA
File "C:\Python33\MyScripts\test2.py", line 4, in <module>
from test1 import mode
File "C:\Python33\MyScripts\test1.py", line 6, in <module>
from test2 import taskA
ImportError: cannot import name taskA
據推測這是由於潛在的圓形性。 (但是,如果它能夠檢測到圓度-在這種情況下就不難了,也就是說,已經導入了taskA,您會認為它能夠簡單地突破圓度,而不是拋出錯誤)。
有沒有辦法做到這一點? 有幾種顯而易見的編碼方法-將其作為一個模塊保存; 將設置作為參數傳遞(但是如果'test2'必須修改任何設置,那將是一個陷阱,前提是Im仍然讓我繼續關注python對可變對象和綁定的處理)。 將所有設置移動到一個單獨的模塊(test0),test1和test2均可訪問。
鑒於這些模塊緊密相連(我相信該術語是緊密耦合的),從邏輯上講,它們應該全部是一個模塊。 除了它越來越大。
我的問題是雙重的……如何最好地做我想做的事; 還要了解為什么Python無法處理相互導入。
(1)嘗試在導入之前移動“ mode = 1”行。 這使得它不再順序依賴於import語句。
(2)如果這不起作用,請將模式放入單獨的程序包中,並從那里同時具有test1和test2導入模式。
基本問題是您已經混合了依賴性級別。 您在“模式”和該模塊中的其他項目之間創建了人為鏈接。
我看不到您在設置“模式”時遇到了麻煩; 我第一次嘗試就做的很好。
test0.py
mode = 2
test1.py
from test0 import mode
from test2 import taskA
mode = 1
ans = taskA()
print(ans)
test2.py
from test0 import mode
def taskA():
print('taska, mode = {0}'.format(mode))
return 'Hello World!'
mode = 0
print('test2 initialised')
執行
>>> python2.7 test1.py
test2 initialised
taska, mode = 0
Hello World!
在您的原始示例中:(A)在test1.py中,將mode = 1行移動到導入之前:
mode = 1
from test2 import taskA
ans = taskA()
print(ans)
此開關表明模式不能依賴模塊taskA中的任何內容,從而打破了病理循環依賴。
(B)使用test2.py作為頂層模塊運行該程序:
>>> python2.7 test2.py
test2 initialised
taska, mode = 0
Hello World!
test2 initialised
這樣可以使您到達想要的位置嗎?
通常,應在有向無環圖(DAG)中設計依賴項。 C可以很簡單,但與此同時可以將標頭( .h)和代碼( .c)文件分開。 這就是為什么我建議第三個文件保存您的“模式”聲明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.