OmegaConf

2.3.0 · active · verified Sun Mar 29

OmegaConf is a flexible configuration library (version 2.3.0) that provides hierarchical configuration, variable interpolation, and merging capabilities from multiple sources like YAML files, CLI arguments, and environment variables. It also offers runtime type safety through Structured Configs. The library is actively maintained with frequent releases, including pre-releases for the upcoming 2.4.0 version.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create configurations from Python dictionaries and YAML strings, access values using dot notation and dictionary-style access, utilize variable interpolation (including environment variables), and create structured configurations using dataclasses for type safety.

from omegaconf import OmegaConf
import os

# Create a config from a dictionary
conf = OmegaConf.create({
    "database": {
        "host": "localhost",
        "port": 5432,
        "user": "${oc.env:DB_USER, default_user}"
    },
    "server": {
        "port": "${database.port}"
    }
})

# Access config values
print(f"Database host: {conf.database.host}")
print(f"Database user: {conf.database.user}") # Resolves from env var or default
print(f"Server port: {conf.server.port}")

# You can also load from YAML strings or files
yaml_string = """
app:
  name: my_app
  version: 1.0
"""
app_conf = OmegaConf.create(yaml_string)
print(f"App name: {app_conf.app.name}")

# Overriding values
conf.database.host = "remote_db"
print(f"Updated database host: {conf.database.host}")

# Example of structured config with dataclasses (requires Python 3.7+ or dataclasses backport for 3.6)
from dataclasses import dataclass

@dataclass
class DatabaseConfig:
    host: str = "127.0.0.1"
    port: int = 5432

@dataclass
class Config:
    db: DatabaseConfig = DatabaseConfig()
    debug: bool = False

structured_conf = OmegaConf.structured(Config)
print(f"Structured config DB host: {structured_conf.db.host}")

# Set an environment variable for testing
os.environ['DB_USER'] = 'my_secret_user'
resolved_user_conf = OmegaConf.create({"db_user": "${oc.env:DB_USER}"})
print(f"Resolved DB user from env: {resolved_user_conf.db_user}")
del os.environ['DB_USER'] # Clean up

view raw JSON →