Skip to main content
Version: 2.3

Load and save configs

Use OmegaConf.create() for a YAML string and OmegaConf.load() for a YAML file. Both return an OmegaConf config:

>>> from omegaconf import OmegaConf
>>> cfg = OmegaConf.create("""
... server:
... port: 80
... """)
>>> cfg.server.port
80

Save and load YAML​

OmegaConf.save(cfg, path) writes YAML, and OmegaConf.load(path) reads it back. Paths, filenames, and file objects are accepted. YAML preserves values but not the Python schema of a structured config. Use OmegaConf.to_yaml(cfg) when you need a YAML string or OmegaConf.to_container(cfg) when another Python API needs ordinary dictionaries and lists.

>>> yaml_text = OmegaConf.to_yaml(cfg)
>>> print(yaml_text, end="")
server:
port: 80

The same operations accept file objects. Loading YAML does not restore a structured config's dataclass or attrs type:

>>> import io
>>> buffer = io.StringIO()
>>> OmegaConf.save(config=cfg, f=buffer)
>>> restored = OmegaConf.load(io.StringIO(buffer.getvalue()))
>>> restored == cfg
True

Convert config to YAML​

OmegaConf.to_yaml(cfg) converts a config to a YAML string. By default (resolve=False), it preserves interpolation expressions, even if you have already accessed their resolved values. This keeps references intact when you save and reload a config.

Pass resolve=True to include the resolved values in the YAML string:

>>> cfg = OmegaConf.create({"port": 80, "url": "http://localhost:${port}"})
>>> cfg.url
'http://localhost:80'
>>> # The default YAML output keeps the interpolation expression.
>>> print(OmegaConf.to_yaml(cfg), end="")
port: 80
url: http://localhost:${port}
>>> # Resolve the interpolation in the YAML output.
>>> print(OmegaConf.to_yaml(cfg, resolve=True), end="")
port: 80
url: http://localhost:80

resolve=True affects the returned YAML string; it does not replace the interpolation in cfg. The config still resolves url using the current port:

>>> cfg.port = 8080
>>> cfg.url
'http://localhost:8080'

To replace interpolations inside the config itself, use OmegaConf.resolve().

Pickle​

A Python-only pickle round trip retains more OmegaConf type information, but the file may not work across OmegaConf versions and must come from a trusted source. On Python 3.6, structured configs with complex type hints cannot be pickled.

>>> import pickle
>>> restored = pickle.loads(pickle.dumps(cfg))
>>> restored == cfg
True