【问题标题】:What is better yaml configuration loading practise?什么是更好的 yaml 配置加载实践?
【发布时间】:2022-01-27 08:59:20
【问题描述】:

您好,

我正在做一个使用 yaml 配置文件的小项目。最近我想知道在 (1) 将先前初始化的配置字典直接加载到模块中,(2) 将配置值作为参数传递或 (3) 其他方式中,哪种做法更好(使代码更具可读性、可扩展性和可维护性)。

示例代码:

config.yml:

my_foo: foo
my_bar: bar

案例(一):

my_config.py:

import yaml

with open(config.yaml, "r") as stream:
    try:
        my_config = yaml.safe_load(stream)
    except yaml.YAMLError as exc:
        print(exc)

my_foo.py:

from my_config import my_config

class MyFoo:
    def __init__(self):
        self.val = my_config[my_foo]

my_bar.py:

from my_config import my_config

class MyBar:
    def __init__(self):
        self.val = my_config[my_bar]

my_main.py:

from my_foo import MyFoo
from my_bar import MyBar

my_foo_instance = MyFoo()
my_bar_instance = MyBar()

案例(2):

my_foo.py:

class MyFoo:
    def __init__(self, val):
        self.val = val

my_bar.py:

class MyBar:
    def __init__(self, val):
        self.val = val

my_main.py:

from my_foo import MyFoo
from my_bar import MyBar

with open(config.yaml, "r") as stream:
    try:
        my_config = yaml.safe_load(stream)
    except yaml.YAMLError as exc:
        print(exc)

my_foo_instance = MyFoo(val=my_config[my_foo])
my_bar_instance = MyBar(val=my_config[my_bar])

【问题讨论】:

  • 该配置是整个项目的配置文件还是仅适用于MyClass?在后一种情况下,我将创建一个类方法,将您的配置文件加载到类上下文中。
  • 我为整个项目使用一个配置文件。我编辑了问题以更好地反映我的情况。
  • 为什么你有两个从同一个配置文件中填充的类?我认为您可能需要详细说明您的用例。事实上,例如,很难确定 MyFoo.val 属性的使用;取决于此,可能根本不需要 YAML 配置文件。

标签: python configuration yaml


【解决方案1】:

我会建议对您的第一个案例进行改进,我认为这比您的第二个案例要好。

config.py:

import yaml

def load_config(path):
    with open(path, "r") as stream:
        # I'm leaving the try-except out because normally 
        # you want your program to fail if the config is incorrect!
        my_config = yaml.safe_load(stream)
    return my_config

main.py:

from my_foo import MyFoo
from my_bar import MyBar
from config import load_config

# Giving the path here is more flexible, you will 
# be able to pass a path as an argument to your program for example
my_config = load_config("my/path.yaml")

my_foo_instance = MyFoo(val=my_config[my_foo])
my_bar_instance = MyBar(val=my_config[my_bar])

【讨论】:

  • 感谢您的回复。我看到您的改进版本比问题中提供的示例代码更好。但是,我关注的重点是将配置导入类和将值作为参数传递之间的区别。您能否提供将配置值作为参数传递的理由?
  • 这有点依赖于项目,一些小项目,例如只执行一个操作的项目,可能希望跨函数/类共享所有配置。但是,如果我们查看流行的工作流框架,例如气流和 dagster,您会发现每个组件(或您的案例中的类)都有专门为其指定的配置。这通常是基于这样的想法,即一个动作不必知道其他动作的任何信息,它们只依赖于明确定义的输入和输出。
  • 所以在实践中,这些框架使用配置文件格式,每个组件都有单独的字段,就像在我的回答中一样,my_foo 字段仅包含 MyFoo 的配置。
猜你喜欢
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
相关资源
最近更新 更多