OmegaConf

raw JSON →
2.3.0 verified Tue May 12 auth: no python install: verified

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.

pip install omegaconf
error ModuleNotFoundError: No module named 'omegaconf'
cause The `omegaconf` package is not installed in the current Python environment or the environment is not correctly activated.
fix
Ensure omegaconf is installed: pip install omegaconf or pip install omegaconf==2.3.0 for a specific version. If using a virtual environment, make sure it's activated.
error omegaconf.errors.ConfigAttributeError: Key 'some_key' is not in struct
cause This error occurs when attempting to access or set a key that is not predefined in a structured config (dataclass/attrs) or when the 'struct' flag is enabled on a DictConfig, which prevents adding new keys dynamically.
fix
If using a structured config, define 'some_key' in your dataclass/attrs schema. If dynamically adding keys to a regular DictConfig that has the 'struct' flag enabled, you can temporarily disable it using with omegaconf.open_dict(cfg): cfg.some_key = value or OmegaConf.set_struct(cfg, False).
error omegaconf.errors.ConfigTypeError: Cannot merge DictConfig with ListConfig
cause This error arises when attempting to merge two `OmegaConf` objects with incompatible types, specifically trying to merge a dictionary-like configuration (`DictConfig`) into a list-like configuration (`ListConfig`) or vice-versa at the same path.
fix
Ensure the structure of the configurations being merged is compatible. If a schema expects a list, the input config at that path must also be a list, not a dictionary, and vice-versa. Adjust either the schema or the input configuration to match types.
error omegaconf.errors.MissingMandatoryValue: Missing mandatory value: some_key
cause A field in a structured config was declared with `MISSING` (e.g., `some_key: int = MISSING`) but was accessed before a value was provided for it.
fix
Provide a value for the mandatory key 'some_key' either in your configuration file, through command-line arguments, or by programmatic assignment before attempting to access it.
error omegaconf.errors.InterpolationValidationError: Value 'string_value' could not be converted to Integer
cause This error occurs in structured configs when an interpolated value, resolved from another part of the config or a resolver, cannot be converted to the Python type annotation specified for that field (e.g., trying to assign a string 'hello' to an `int` field).
fix
Ensure that the value being interpolated is compatible with the target field's type. If the interpolated value is a string that represents a number, it will be automatically converted. If it's a non-numeric string, the type annotation of the target field should be str.
breaking In OmegaConf 2.1, accessing non-existent keys via `DictConfig.__getattr__` (e.g., `cfg.non_existent_key`) now raises an `AttributeError`, and `DictConfig.__getitem__` (e.g., `cfg['non_existent_key']`) raises a `KeyError`. Previously, these operations returned `None`.
fix Update code to use `cfg.get('key', default_value)` or `if 'key' in cfg:` / `hasattr(cfg, 'key')` for existence checks, or handle `AttributeError`/`KeyError`.
breaking As of OmegaConf 2.1, the `OmegaConf.select()` method requires keyword arguments for all parameters after the `key`. Positional arguments for `default` and `throw_on_missing` are no longer supported.
fix Change calls from `OmegaConf.select(cfg, 'path', 'default')` to `OmegaConf.select(cfg, 'path', default='default')`.
gotcha OmegaConf objects (`DictConfig`, `ListConfig`) are not native Python `dict` or `list` instances. Direct usage with APIs expecting standard Python containers can lead to unexpected behavior. They also retain OmegaConf's specific features like interpolation and type safety.
fix Use `OmegaConf.to_container(cfg, resolve=True)` to convert an OmegaConf object to a plain Python `dict` or `list`, optionally resolving interpolations during conversion. For structured configs, `OmegaConf.to_object()` can convert to the original dataclass/attrs instance.
gotcha In OmegaConf 2.2.1, implicit conversion from `pathlib.Path` objects to `str` was disallowed, leading to `ValidationError` when assigning a `Path` to a string-typed structured config field. This behavior was reverted in versions 2.2.2 and 2.2.3, restoring the implicit conversion.
fix If encountering issues in 2.2.1, explicitly cast `Path` to `str` (e.g., `str(my_path)`) or upgrade to 2.2.2+ where the implicit conversion is restored.
gotcha Structured configs with complex type hints (e.g., nested container types, containers with optional element types) cannot be pickled on Python 3.6 due to limitations in Python's pickling support for such types.
fix Use Python 3.7+ for pickling complex structured configs, or ensure type hints are simple enough for Python 3.6 if pickling is required.
gotcha The `???` syntax indicates a mandatory value in the configuration. Accessing a mandatory value that has not been set (either directly or via interpolation/CLI overrides) will raise a `MissingMandatoryValue` exception at runtime.
fix Ensure all mandatory `???` values are provided through configuration files, command-line arguments, or environment variables before being accessed. Handle `MissingMandatoryValue` exceptions if dynamic resolution is expected.
gotcha When defining dataclasses for structured configurations, using mutable objects (like instances of custom classes, lists, or dictionaries) as default values for fields will raise a `ValueError: mutable default ... is not allowed`. This is a standard Python dataclass limitation, not specific to OmegaConf, but frequently encountered when defining structured configs.
fix Use `default_factory` for mutable default values in dataclasses. For example, instead of `field: MyClass = MyClass()`, use `field: MyClass = field(default_factory=MyClass)`.
python os / libc status wheel install import disk
3.10 alpine (musl) sdist - 0.22s 23.1M
3.10 alpine (musl) - - 0.24s 23.1M
3.10 slim (glibc) sdist 2.3s 0.15s 24M
3.10 slim (glibc) - - 0.17s 24M
3.11 alpine (musl) sdist - 0.41s 26.1M
3.11 alpine (musl) - - 0.49s 26.1M
3.11 slim (glibc) sdist 2.4s 0.38s 27M
3.11 slim (glibc) - - 0.36s 27M
3.12 alpine (musl) sdist - 0.30s 16.0M
3.12 alpine (musl) - - 0.33s 16.0M
3.12 slim (glibc) sdist 3.4s 0.33s 17M
3.12 slim (glibc) - - 0.36s 17M
3.13 alpine (musl) sdist - 0.28s 15.7M
3.13 alpine (musl) - - 0.31s 15.6M
3.13 slim (glibc) sdist 3.0s 0.30s 17M
3.13 slim (glibc) - - 0.32s 17M
3.9 alpine (musl) sdist - 0.21s 22.7M
3.9 alpine (musl) - - 0.24s 22.7M
3.9 slim (glibc) sdist 2.8s 0.20s 24M
3.9 slim (glibc) - - 0.20s 24M

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