我的代碼結構如下:main.pyutils.pyblah.py該main模塊使用 argparse 讀取配置 yaml 文件的位置,然后將其作為字典加載。utils有沒有辦法blah導入這個內置的字典?編輯:我嘗試使用from main import config(配置是我構建的字典)但我得到了ImportError: cannot import name 'config' from 'main'Edit2:主要導入其他 2 個模塊 - 很抱歉遺漏了這個非常重要的細節
2 回答

qq_遁去的一_1
TA貢獻1725條經驗 獲得超8個贊
我建議制作另一個文件,例如globals.py. 將其導入main、utils和blah,并在其中設置屬性以供其他模塊調用。例如:
globals.py
configs = {}
main.py
import .globals
...
user_configs = yaml.load('user/entered/path.yml')
globals.configs.update(user_configs) # modifies the global `configs` variable
utils.py
import .globals
...
# need to use one of the configs for something:
try:
relevant_config = globals.configs['relevant_config']
except KeyError:
print("User did not input the config field 'relevant_config'")
所有模塊都將能夠看到相同的globals實例,從而允許您在整個程序中使用有效的全局變量。
您可以簡單地將其保存configs為 gobal 變量,main.py并擁有utils.py和blah.py導入.main,但是為此指定一個模塊比讓其他模塊導入主模塊更干凈、更清晰。
添加回答
舉報
0/150
提交
取消