最近在重构RapidOCR仓库代码,使其更加优雅的同时,具有扩展性。无意从他人源码中发现omegaconf库。
omegaconf
OmegaConf是一个用于处理配置文件和命令行参数的Python库。它支持YAML、JSON、INI等多种配置文件格式,提供了配置合并、类型安全的配置访问、环境变量插值等高级功能。通过OmegaConf,开发人员可以更方便地管理和访问配置文件中的信息,从而简化应用程序的配置管理。
官方文档
https://omegaconf.readthedocs.io/en/2.3_branch/
常用代码段
from omegaconf import OmegaConf
# 加载配置文件
cfg = OmegaConf.load('config.yaml')
# 访问配置信息
print(cfg.database.host) # 输出:localhost
print(cfg.database.port) # 输出:3306
# 修改配置信息
cfg.database.port = 3307
print(cfg.database.port) # 输出:3307
# 保存修改后的配置信息
with open('config_modified.yaml', 'w') as f:
omegaconf.OmegaConf.save(cfg, f)
与dataclasses
类联合使用
class Height(Enum):
SHORT = 0
TALL = 1
@dataclass
class SimpleTypes:
num: int = 10
pi: float = 3.1415
is_awesome: bool = True
height: Height = Height.SHORT
description: str = "text"
data: bytes = b"bin_data"
path: pathlib.Path = pathlib.Path("hello.txt")
conf1 = OmegaConf.structured(SimpleTypes)
conf2 = OmegaConf.structured(SimpleTypes())
# The two configs are identical in this case
assert conf1 == conf2
# But the second form allow for easy customization of the values:
conf3 = OmegaConf.structured(
SimpleTypes(num=20,
height=Height.TALL))
print(OmegaConf.to_yaml(conf3))
# 输出
num: 20
pi: 3.1415
is_awesome: true
height: TALL
description: text
data: !!binary |
YmluX2RhdGE=
path: !!python/object/apply:pathlib.PosixPath
- hello.txt