omegaconf库使用实践

最近在重构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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值