我有一个大型项目,我从 config.ini 加载一些变量,例如生成的数据的 target_directory。该 target_directory 在整个项目中使用,但并不总是设置在同一位置。它可以通过 config.ini 设置,但可以通过命令行参数或单元测试覆盖。
以全局方式保留该状态的最佳方法是什么,这样我就不必将其传递到程序的每个函数中。
该程序由许多不同的模块和包组成,我想知道是否有最佳实践来处理这个问题。
最佳答案
您可以使用字典或任何其他类型的 container 将状态设置为模块级变量。 。这些值不是静态的,可以通过任何有权访问它们的代码进行修改/变异(除非您使用不可变的容器,例如元组或命名元组)。您可以使用 import conf
导入整个 conf.py
模块,或者使用 from conf import CONFIG
# this is conf.py
import argparse
import configparser
CONFIG = {}
def build_config():
# ...compose your config from cli, ini file, etc
CONFIG['option_one'] = 'hello world'
return CONFIG
...
# this is a.py
import conf
def do_something_with_config_value():
return conf.CONFIG['option_one']
...
# this is b.py
import a
import conf
if __name__ == '__main__':
conf.build_config()
print(a.do_something_with_config_value())
关于python - 在大型 python 程序中保存状态而不将变量作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46853738/