
OmegaConf 是一个基于 YAML 的分层配置系统,核心优势在于支持变量插值 、配置合并 及结构化配置(类型安全)。它常用在机器学习、深度学习项目中管理复杂的配置。
安装与创建
-
安装 :
pip install omegaconf(需要 Python 3.8+) -
创建配置 :
OmegaConf提供了create()方法,可以从字典、列表、YAML字符串等多种来源创建配置对象。from omegaconf import OmegaConf
从字典创建
conf = OmegaConf.create({
"server": {"host": "localhost", "port": 80},
"users": ["user1", "user2"]
})
print(OmegaConf.to_yaml(conf))
输出:
server:
host: localhost
port: 80
users:
- user1
- user2
读取与保存文件
-
加载 YAML 文件 :使用
OmegaConf.load('config.yaml')。 -
保存 YAML 文件 :使用
OmegaConf.save(config=conf, f='output.yaml')。
核心功能
-
灵活访问
-
属性风格 :
conf.server.port -
字典风格 :
conf['server']['port'] -
列表元素:
conf.users[0]
-
-
变量插值 (Variable Interpolation)
允许配置值引用配置中的其他部分,实现动态配置。
文件: config.yaml
server:
host: localhost
port: 8080
client:
# 引用 server.host 和 server.port
url: http://${server.host}:{server.port}/ # 相对引用,引用同级的 url description: Client of {.url}conf = OmegaConf.load('config.yaml')
print(conf.client.url) # http://localhost:8080/ -
配置合并 (Config Merging)
通过 OmegaConf.merge() 将多个配置合并,常用于覆盖默认配置。
default_conf = OmegaConf.create({"a": 1, "b": 2})
override_conf = OmegaConf.create({"b": 20, "c": 3})
final_conf = OmegaConf.merge(default_conf, override_conf)
print(final_conf) # {'a': 1, 'b': 20, 'c': 3}
Python 3.11+ 也支持使用 | 和 |= 运算符进行合并。
-
解析命令行参数
通过
OmegaConf.from_cli()可以将命令行参数解析为配置对象,方便实验调参。假设命令行输入: python my_app.py server.port=82
conf = OmegaConf.from_cli()
print(conf.server.port) # 82
进阶特性:结构化配置 (Structured Configs)
结构化配置通过 Python 的 dataclass 或 attrs 定义配置的类型和结构 ,提供运行时类型安全和更好的 IDE 支持。
from dataclasses import dataclass
from omegaconf import OmegaConf, SI
@dataclass
class MySQLConfig:
host: str = "localhost"
port: int = 3306
user: str = "root"
# SI 是字符串插值的便捷包装,保证类型检查器通过
url: str = SI("jdbc:mysql://${host}:${port}/")
# 创建结构化配置实例
conf = OmegaConf.structured(MySQLConfig)
print(conf.port) # 3306
conf.port = 3307 # OK
# conf.port = "oops" # 类型不匹配,会抛出 ValidationError