使用rumael.yaml向使用omegaconfig生成的yaml添加注释

2024-05-19 08:10:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用omegaconfig从python数据类生成yaml配置,但我注意到无法在生成的yaml文件中添加注释

我正在寻找一种方法来获取生成的yaml配置字符串,并向不同的节和值添加注释。我曾考虑使用regex,但我遇到了一个问题,我有一个小节,后面跟着一个小节,我必须小心我写评论的顺序(我的第一个想法是从一个类“uuu doc”中解析它们,但现在如果我认为更好,这不是一个好主意,我认为用rumael.yaml这样做会更好,但是怎么做呢

从obegaconfig文档可以看出,从数据类生成配置的工作方式如下:

  from dataclasses import dataclass
>>> @dataclass
... class MyConfig:
...     port: int = 80
...     host: str = "localhost"
>>> # For strict typing purposes, prefer OmegaConf.structured() when creating structured configs
>>> conf = OmegaConf.structured(MyConfig)
>>> print(OmegaConf.to_yaml(conf))
port: 80
host: localhost

如何使用rumael.yaml向生成的yaml注释中注入

如果有一种方法可以从以下位置解析MyConfig类上的__doc,那就太好了:

"""
port: This is a comment
host: This is another comment
section.another: Commenting a value under a base section
"""

并将其自动添加到我的yaml文件中,这样它将以如下方式结束:

port: 80 #this is a comment
host: localhost #this is another comment
section:
    another: #commenting a value under a base section

Tags: 文件数据方法localhosthostyamlisport

热门问题