python - 在大型 python 程序中保存状态而不将变量作为参数传递

标签 python

我有一个大型项目,我从 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/

相关文章:

python - 为什么cv2.resize()对整数数组不起作用?

python - 没有 modelform 的 Django 表单集无法工作

Python 可执行文件作为 Windows 服务

用于字符串修改的 Python 代码无法正常工作

python - 递归算法中Python列表的可变性

python - 如何在 python3 中检索类类型的子类?

python - tensorflow 2 : Getting "WARNING:tensorflow:9 out of the last 9 calls to <function> triggered tf.function retracing. Tracing is expensive"

python - 如何循环遍历所有列表项并从每个键中提取值?

python - 仅通过插入和删除来查找编辑距离的变化?

python邮件没有主题通过