繁体   English   中英

如何将我的代码组织到多个文件中以共享一个公共的全局变量

[英]how to organize my code into multiple files to share a common global variable


与线程或多处理无关,不会有任何并发问题。 这更多是关于如何在项目中组织 python 文件的问题。

意图:
共享 var 是一个全局字典global_dict
我的整个代码是简单地设置这个字典并在以后使用它,就像下面的伪代码一样简单:

global_dict = {}

########################### FIRST PORTION OF THE CODE ###########################

# [step 0] 
lengthy computations and file ios to compute the keyname and content to be added to global_dict
global_dict['keyname00'] = content00

# [step 1] 
distinct from other steps lengthy computations and file ios to compute the keyname and content to be added to global_dict
global_dict['keyname01'] = content01

....

# [step ##] 
distinct from other steps lengthy computations and file ios to compute the keyname and content to be added to global_dict
global_dict['keyname##'] = content##

########################### SECOND PORTION OF THE CODE ###########################
# now we have setup the dictionary, we can use it here
myclass = myclass(global_dict)
myclass.dostuff()

我想达到的目标:
我无法将设置global_dict的所有代码(即[step ##]代码)放入一个 python 文件中,太长且难以导航,我必须将其分开。

到目前为止我所做的尝试:
我已将单个文件分成多个文件:

file global_dict.py

global_dict = {}

file step00.py

from global_dict import global_dict
lengthy computations and file ios to compute the keyname and content to be added to global_dict
global_dict['keyname00'] = content00

file step01.py ... file step##.py

from global_dict import global_dict
lengthy computations and file ios to compute the keyname and content to be added to global_dict
global_dict['keyname##'] = content##

mainline.py

from global_dict import global_dict
for pyfile in current working dir:
    importlib.import_module(pyfile)

上面的代码工作正常,但感觉笨拙和不安,但想不出更好的方法。 需要帮忙。

PS global_dict的内容不可腌制。

感谢您提供有用的建议,但我相信我过于简化了我的实际代码。 在我的实际代码中,我确实在每个step##.py中都有一个inline()main() function 来处理字典的修改。 因此,在我的main.py中,我因此调用了所有step##.py

for fp in sorted( # fp: filepath of all the setup py files
        (path_setups).glob('*.py')
    ):
    if fp.stem != '__init__':
        setup = importlib.import_module('sigs.inline_setups.' + fp.stem)
        logging.info(setup)
        setup.inline() # <========= inline() is the func that modifies `global_dict`

您应该以相反的方式执行此操作,修改您的代码,以便您可以遵循以下模式:

import step00
import step01
import step02

global_dict = {}

step00.main()
step01.main()
step02.main()

那会做你想做的事。 但是,很容易“改进”您的代码,使其也不需要全局字典:

import step00
import step01
import step02

my_dict = {}

step00.main(my_dict)
step01.main(my_dict)
step02.main(my_dict)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM