python - 如何在Python中管理全局变量

标签 python configuration global-variables data-science

我正在开发一个数据科学项目,该项目有大量数据预处理和神经网络实现,并生成 png 文件形式的图表。项目由近 30 多个 python 脚本组成。 我有一组通用值,我需要在全局范围内几乎每个脚本中使用它们。

因此,我创建了一个 config.yaml 文件来存储值,并创建了 util.py 文件来读取 yaml 文件并分配值作为全局变量。

config.yaml 的一部分

config:
    input_src: "./input_data"
    data_output: "./final_output"
    tempory_src: "./tmp_files"
    neural_network_model_version: "NeuralNet_v1907"
    all_store_output: "/all_store"
    single_store_output: "/individual"

util.py

with open('config.yaml',encoding="utf-8_sig") as f:

    data = yaml.load(f, Loader=yaml.FullLoader)
    global input_src
    global output_src
    global model_version
    global all_store_output
    global single_store_output
    global temp_src
    config=data["config"]

    input_src=config["input_src"]
    output_src=config["data_output"]
    model_version = config["neural_network_model_version"]
    all_store_output= config["all_store_output"]
    single_store_output= config["single_store_output"]

当我导入 util 文件时,它具有所有全局变量。

我知道拥有大量全局变量不是一个好习惯。我需要知道管理这种情况最合适和推荐的方法是什么。

最佳答案

最简单的方法可能是将所有设置放入一个字典或数据类中。

另一种选择是使用函数加载设置,然后缓存结果:

from functools import lru_cache

import yaml


@lru_cache()
def load_config(config_path='config.yaml'):
    with open(config_path, encoding="utf-8_sig") as f:
        data = yaml.load(f, Loader=yaml.FullLoader)

    # TODO: validate values and calculate related values

    print('Config loaded.')  # Just to show that it only loads once.
    return data['config']

def foo():
    config = load_config()
    print(config['input_src'])

def bar():
    config = load_config()
    print(config['data_output'])

def main():
    foo()
    bar()

main()

如果您不喜欢挖掘该字典来获取所有设置,您可以将所有设置放入类的属性中,或者编写更多函数以从主设置字典中获取每个设置。

关于python - 如何在Python中管理全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58336675/

相关文章:

python - 在 Python 中设置数据库连接超时

python - Sqlalchemy mySQL 优化查询

android - 我如何在 Android 模拟器中配置 gmail?

java - Eclipse for Java 显示多个错误

deployment - 如何在组织范围内处理特定环境的应用程序配置?

c++ - 如何在第三方库调用的回调函数中传递/使对象/变量可访问?

python - 变压器 : cannot import name 'AutoModelWithLMHead' from 'transformers'

python - 使用 Inno Setup 安装 Python

c - C 中的 Extern - 我做错了什么?

node.js - 找不到变量 : Buffer