OmegaConf:从基础到进阶
1. OmegaConf 简介
OmegaConf 是 hydra
背后的核心配置库,提供比 argparse
和 json.load
更灵活的配置管理能力。其主要特性包括:
安装 OmegaConf:
bash
pip install omegaconf
2. 基本操作
2.1 创建 OmegaConf 配置
OmegaConf 提供两种主要的数据结构:
DictConfig
(字典格式)ListConfig
(列表格式)
2.1.1 从字典创建配置
python
from omegaconf import OmegaConf
config = OmegaConf.create({
"name": "Alice",
"age": 25,
"skills": ["Python", "Machine Learning"],
"details": {
"location": "USA",
"experience": 5
}
})
print(config.name) # Alice
print(config.details.location) # USA
2.1.2 从 YAML 字符串创建配置
python
yaml_config = """
name: Bob
age: 30
skills:
- Java
- DevOps
details:
location: Canada
experience: 8
"""
config = OmegaConf.create(yaml_config)
print(config.skills[1]) # DevOps
2.1.3 读取YAML文件配置
python
from omegaconf import OmegaConf
config = OmegaConf.load("config.yaml")
2.1.4 读取 JSON 配置
python
json_config = '{"name": "Charlie", "age": 28, "skills": ["Go", "Docker"]}'
config = OmegaConf.create(json_config)
print(config.skills) # ['Go', 'Docker']
2.1.5 保存YAML文件
python
OmegaConf.save(config, "config.yaml")
3. 访问和修改配置
3.1 访问配置值
OmegaConf 允许使用 点运算符 和 字典索引 访问值:
python
print(config.name) # Charlie
print(config["age"]) # 28
3.2 修改配置值
python
config.name = "Dave"
config["age"] = 35
print(config.name) # Dave
3.3 添加新键值
python
config.country = "Germany"
config["city"] = "Berlin"
print(config) # {'name': 'Dave', 'age': 35, 'skills': ['Go', 'Docker'], 'country': 'Germany', 'city': 'Berlin'}
4. 变量插值(Interpolation)
OmegaConf 支持变量插值 ,即使用 ${}
访问配置中的其他值。
python
yaml_with_interpolation = """
name: Eve
greeting: "Hello, ${name}!"
"""
config = OmegaConf.create(yaml_with_interpolation)
print(config.greeting) # Hello, Eve!
数学计算插值:
python
yaml_math = """
a: 10
b: 5
sum: ${a} + ${b}
"""
config = OmegaConf.create(yaml_math)
print(config.sum) # 15
5. 配置合并(Merge)
OmegaConf 允许合并多个配置文件,例如默认配置 和用户自定义配置。
python
default_config = OmegaConf.create({"learning_rate": 0.01, "batch_size": 32})
user_config = OmegaConf.create({"batch_size": 64, "epochs": 10})
merged_config = OmegaConf.merge(default_config, user_config)
print(merged_config) # {'learning_rate': 0.01, 'batch_size': 64, 'epochs': 10}
6. 结构化配置(Typed Config)
6.1 定义数据类并加载配置
OmegaConf 支持 Python dataclass
,使配置更加结构化。
python
from dataclasses import dataclass
from omegaconf import OmegaConf
@dataclass
class ModelConfig:
learning_rate: float = 0.01
batch_size: int = 32
config = OmegaConf.structured(ModelConfig)
print(config.learning_rate) # 0.01
6.2 合并结构化配置
python
@dataclass
class TrainingConfig:
model: ModelConfig
epochs: int = 10
default_cfg = OmegaConf.structured(TrainingConfig)
user_cfg = OmegaConf.create({"model": {"batch_size": 64}, "epochs": 20})
merged_cfg = OmegaConf.merge(default_cfg, user_cfg)
print(merged_cfg) # {'model': {'learning_rate': 0.01, 'batch_size': 64}, 'epochs': 20}
7. 进阶操作
7.1 保护只读配置
python
cfg = OmegaConf.create({"param": 42})
OmegaConf.set_readonly(cfg, True)
# 下面的操作会报错
# cfg.param = 100
7.2 使用环境变量
OmegaConf 可以解析环境变量:
python
import os
os.environ["DB_HOST"] = "localhost"
yaml_env = """
database:
host: ${oc.env:DB_HOST}
"""
config = OmegaConf.create(yaml_env)
print(config.database.host) # localhost
7.3 递归解析(resolve)
OmegaConf 默认不会解析变量插值,需手动启用:
python
cfg = OmegaConf.create({"a": 10, "b": "${a} + 5"})
print(cfg.b) # ${a} + 5
cfg_resolved = OmegaConf.to_container(cfg, resolve=True)
print(cfg_resolved["b"]) # 15
8. OmegaConf vs. 其他配置管理工具
特性 | OmegaConf | argparse | json | YAML |
---|---|---|---|---|
支持嵌套 | ✅ | ❌ | ✅ | ✅ |
变量插值 | ✅ | ❌ | ❌ | ❌ |
类型安全 | ✅ | ❌ | ❌ | ❌ |
合并配置 | ✅ | ❌ | ❌ | ❌ |
结构化支持 | ✅ | ❌ | ❌ | ❌ |