OmegaConf 是一个 Python 库,用于处理配置文件和配置数据,特别适合管理层次化的配置结构。它是 Hydra 配置框架的核心组件,但也可以独立使用。
主要特性
- 配置合并:支持合并多个配置源
- 变量插值:支持在配置中引用其他值
- 运行时修改:可以在运行时修改配置
- 多种格式支持:YAML、JSON、字典等
- 类型安全:支持类型检查和转换
安装
pip install omegaconf
1. 基本用法
(1)从字典创建配置
from omegaconf import OmegaConf
# 从字典创建
cfg = OmegaConf.create({"a": 1, "b": {"c": 2}})
print(cfg.a) # 输出: 1
print(cfg.b.c) # 输出: 2
(2). 从 YAML 文件加载
假设有一个 config.yaml 文件:
server:
host: localhost
port: 8080
database:
name: test
user: admin
加载配置:
cfg = OmegaConf.load("config.yaml")
print(cfg.server.host) # 输出: localhost
(3) 合并多个配置
base_cfg = OmegaConf.create({"a": 1, "b": 2})
override_cfg = OmegaConf.create({"b": 3, "c": 4})
merged = OmegaConf.merge(base_cfg, override_cfg)
print(merged) # {'a': 1, 'b': 3, 'c': 4}
base = OmegaConf.load("base_config.yaml")
dev = OmegaConf.load("dev_config.yaml")
cfg = OmegaConf.merge(base, dev)
print(cfg.app.log_level) # DEBUG (覆盖了base的INFO)
print(cfg.database.host) # dev.db.example.com (覆盖了base的localhost)
(4) 访问和修改配置
cfg = OmegaConf.create({"a": 1, "b": {"c": 2}})
# 访问
print(cfg.a) # 1
print(cfg.b.c) # 2
# 修改
cfg.a = 10
cfg.b.c = 20
# 添加新字段
cfg.d = "new field"
(5) 变量插值 (用的比较少)
cfg = OmegaConf.create({
"server": {
"host": "localhost",
"port": 8080,
"url": "${server.host}:${server.port}"
}
})
print(cfg.server.url) # 输出: localhost:8080
- 环境变量插值
cfg = OmegaConf.create({
"database": {
"password": "${oc.env:DB_PASSWORD,default_password}"
}
})
# 如果环境变量 DB_PASSWORD 存在则使用它,否则使用 default_password
2. to_container 方法
OmegaConf.to_container() 是将 OmegaConf 配置对象转换为原生 Python 数据结构的核心方法,它可以将 OmegaConf 的特殊容器类型(如 DictConfig 和 ListConfig)转换为标准的 Python dict 和 list。
self.conf = OmegaConf.load(self.vc_config)
(Pdb) type(self.conf)
<class 'omegaconf.dictconfig.DictConfig'>
得到的conf对象的类型是'omegaconf.dictconfig.DictConfig'
, 支持cfg.a
的形式访问对象。如果需要转换成python 的数据类型,则需要OmegaConf.to_container
转换,此时得到的数据类型为dict
, 此时通过cfg[‘a’]
self.conf = OmegaConf.to_container(self.conf, resolve=True)
(Pdb) type(self.conf)
<class 'dict'>
案例:
from omegaconf import OmegaConf
# 创建 OmegaConf 配置对象
cfg = OmegaConf.create({
"server": {
"host": "localhost",
"port": 8080
},
"features": ["auth", "logging"]
})
# 转换为原生 Python 容器
python_dict = OmegaConf.to_container(cfg)
print(type(python_dict)) # <class 'dict'>
print(python_dict)
# 输出: {'server': {'host': 'localhost', 'port': 8080}, 'features': ['auth', 'logging']}
- resolve (默认为 False): 是否解析所有插值变量,默认为不解析
cfg = OmegaConf.create({
"host": "localhost",
"port": 8080,
"url": "${host}:${port}"
})
# 不解析插值
result = OmegaConf.to_container(cfg, resolve=False)
print(result["url"]) # ${host}:${port}
# 解析插值
result = OmegaConf.to_container(cfg, resolve=True)
print(result["url"]) # localhost:8080