API Reference¶
The OmegaConf API¶
- class omegaconf.OmegaConf[source]¶
OmegaConf primary class
- static can_select(cfg: Container, key: str, *, throw_on_resolution_failure: bool = True, throw_on_missing: bool = False) bool[source]¶
Return
TrueifOmegaConf.select()can select a value from a config.This uses the same key path syntax and behavior flag names as
select()for convenience, butcan_select()does not raise for select failures. It returnsFalseinstead of raising or returning a default when the path cannot be selected. A selectedNonevalue counts as selectable.- Parameters:
cfg – Config node to select from
key – Key path to select (dot/bracket notation, backslash-escapable)
throw_on_resolution_failure – Treat an interpolation resolution error as not selectable
throw_on_missing – Treat selecting a missing key (with the value ‘???’) as not selectable
- Returns:
Trueif the key can be selected, otherwiseFalse.
- static clear_cache(conf: BaseContainer) None[source]¶
Clear the resolver cache for
conf.- Parameters:
conf – An OmegaConf container.
- classmethod clear_resolver(name: str) bool[source]¶
Clear(remove) any resolver only if it exists.
Returns a bool: True if resolver is removed and False if not removed.
- Parameters:
name – Name of the resolver.
- Returns:
A bool (
Trueif resolver is removed,Falseif not found before removing).
- static clear_resolvers() None[source]¶
Clear(remove) all OmegaConf resolvers, then re-register OmegaConf’s default resolvers.
- static copy_cache(from_config: BaseContainer, to_config: BaseContainer) None[source]¶
Copy the resolver cache from one config to another.
- Parameters:
from_config – Source container whose cache is copied.
to_config – Destination container that receives the cache copy.
- static create(obj: str, parent: BaseContainer | None = None, flags: Dict[str, bool] | None = None, *, max_yaml_expanded_nodes: int | None = _DEFAULT_MAX_YAML_EXPANDED_NODES) DictConfig | ListConfig[source]¶
- static create(obj: List[Any] | Tuple[Any, ...], parent: BaseContainer | None = None, flags: Dict[str, bool] | None = None, *, max_yaml_expanded_nodes: int | None = _DEFAULT_MAX_YAML_EXPANDED_NODES) ListConfig
- static create(obj: DictConfig, parent: BaseContainer | None = None, flags: Dict[str, bool] | None = None, *, max_yaml_expanded_nodes: int | None = _DEFAULT_MAX_YAML_EXPANDED_NODES) DictConfig
- static create(obj: ListConfig, parent: BaseContainer | None = None, flags: Dict[str, bool] | None = None, *, max_yaml_expanded_nodes: int | None = _DEFAULT_MAX_YAML_EXPANDED_NODES) ListConfig
- static create(obj: None, parent: BaseContainer | None = None, flags: Dict[str, bool] | None = None, *, max_yaml_expanded_nodes: int | None = _DEFAULT_MAX_YAML_EXPANDED_NODES) None
- static create(obj: Dict[Any, Any] = _DEFAULT_MARKER_, parent: BaseContainer | None = None, flags: Dict[str, bool] | None = None, *, max_yaml_expanded_nodes: int | None = _DEFAULT_MAX_YAML_EXPANDED_NODES) DictConfig
Create an OmegaConf config from
obj.objmay be a YAML string, a dict, a list or tuple, a dataclass or attrs class (type or instance), an existingDictConfig/ListConfig, orNone. Omittingobj(or passing{}explicitly) returns an emptyDictConfig.- Parameters:
obj – Source object to build the config from.
parent – Optional parent node.
flags – Optional flags dict (e.g.
{"readonly": True}).max_yaml_expanded_nodes – Maximum YAML nodes after alias expansion when
objis a YAML string. By default, OmegaConf uses theOMEGACONF_MAX_YAML_EXPANDED_NODESenvironment variable if set, otherwise10_000. Explicit arguments override the environment. PassNoneonly for trusted input. See https://omegaconf.readthedocs.io/en/latest/yaml_aliases.html.
- Returns:
A
DictConfig,ListConfig, orNone(whenobjisNone).
- static from_cli(args_list: List[str] | None = None) DictConfig[source]¶
Create a config from command-line arguments (
sys.argv[1:]by default).Each argument must be a dotlist-style string such as
"foo.bar=1".- Parameters:
args_list – Explicit list of dotlist strings; defaults to
sys.argv[1:].- Returns:
A
DictConfigbuilt from the arguments.
- static from_dotlist(dotlist: List[str]) DictConfig[source]¶
Creates a config from a list of dotlist-style strings (
"key=value"pairs).Each entry is split on the first unescaped
=. Everything before it is the key path; everything after it is the value. Key paths follow the same dot/bracket syntax asselect()andupdate().Backslash escaping in keys: Use a backslash to include a literal special character in a key name. The escapable characters are
.,[,], and=.r"a\.b=1"— key is"a.b"(dot is part of the key)r"a\=b=1"— key is"a=b"(=is part of the key; the second=is the key/value separator)
Values may contain
=freely; only the first unescaped=separates key from value (e.g."url=http://x?a=1"gives keyurl, valuehttp://x?a=1).CLI / shell note: When using
from_cli(), arguments pass through the shell before reaching Python. A single backslash in a shell argument is usually consumed by the shell, so you must double it (\\) or quote the argument ('a\.b=1') to preserve it.- Parameters:
dotlist – A list of dotlist-style strings, e.g.
["foo.bar=1", "baz=qux"].- Returns:
A
DictConfigobject created from the dotlist.
- static get_cache(conf: BaseContainer) Dict[str, Any][source]¶
Return the resolver cache for
conf.- Parameters:
conf – An OmegaConf container.
- Returns:
The resolver cache dict (resolver name -> cached values).
- static get_type(obj: Any, key: str | None = None) Type[Any] | None[source]¶
Return the type of
obj, or ofobj[key]whenkeyis provided.For structured configs this is the underlying dataclass or attrs class. For plain containers it is
dictorlist.- Parameters:
obj – An OmegaConf node or container.
key – Optional key within
objto inspect.
- Returns:
The Python type, or
Noneif not determinable.
- classmethod has_resolver(name: str) bool[source]¶
Return
Trueif a resolver with the given name is registered.- Parameters:
name – Resolver name to check.
- Returns:
Trueif registered,Falseotherwise.
- static is_config(obj: Any) bool[source]¶
Return
Trueifobjis an OmegaConf config (DictConfigorListConfig).- Parameters:
obj – Object to test.
- Returns:
Trueifobjis an OmegaConf container,Falseotherwise.
- static is_dict(obj: Any) bool[source]¶
Return
Trueifobjis an OmegaConfDictConfig.- Parameters:
obj – Object to test.
- Returns:
Trueifobjis aDictConfig,Falseotherwise.
- static is_interpolation(node: Any, key: str | int | None = None) bool[source]¶
Return
Trueif the target node is an interpolation (e.g.${foo.bar}).If
keyis provided, checksnode[key]; otherwise checksnodeitself.- Parameters:
node – An OmegaConf node, or a container when
keyis given.key – Optional key within
nodeto inspect.
- Returns:
Trueif the value is an interpolation,Falseotherwise.
- static is_list(obj: Any) bool[source]¶
Return
Trueifobjis an OmegaConfListConfig.- Parameters:
obj – Object to test.
- Returns:
Trueifobjis aListConfig,Falseotherwise.
- static is_missing(cfg: Any, key: str | bytes | int | Enum | float | bool) bool[source]¶
Return
Trueifcfg[key]is set to the mandatory-missing sentinel???.- Parameters:
cfg – An OmegaConf container.
key – Key (str for DictConfig, int for ListConfig) to check.
- Returns:
Trueif the value is missing,Falseotherwise.
- static is_readonly(conf: Node) bool | None[source]¶
Return the effective read-only flag of
conf.- Parameters:
conf – An OmegaConf node.
- Returns:
Trueif read-only,Falseif writable,Noneif not set (inherits from parent).
- static is_struct(conf: Container) bool | None[source]¶
Return the effective struct flag of
conf.- Parameters:
conf – An OmegaConf container.
- Returns:
Trueif struct mode is on,Falseif off,Noneif not set (inherits from parent).
- static load(file_: str | Path | IO[Any], *, max_yaml_expanded_nodes: int | None = 10000) DictConfig | ListConfig[source]¶
Load a YAML config from a file path or file-like object.
- Parameters:
file – A file path (str or
pathlib.Path) or an open file object.max_yaml_expanded_nodes – Maximum YAML nodes after alias expansion. By default, OmegaConf uses the
OMEGACONF_MAX_YAML_EXPANDED_NODESenvironment variable if set, otherwise10_000. Explicit arguments override the environment. PassNoneonly for trusted input. See https://omegaconf.readthedocs.io/en/latest/yaml_aliases.html.
- Returns:
A
DictConfigorListConfigparsed from the YAML content.
- static masked_copy(conf: DictConfig, keys: str | List[str]) DictConfig[source]¶
Create a masked copy of of this config that contains a subset of the keys
- Parameters:
conf – DictConfig object
keys – keys to preserve in the copy
- Returns:
The masked
DictConfigobject.
- static merge(*configs: DictConfig | ListConfig | Dict[str | bytes | int | Enum | float | bool, Any] | List[Any] | Tuple[Any, ...] | Any, list_merge_mode: ListMergeMode = ListMergeMode.REPLACE) ListConfig | DictConfig[source]¶
Merge a list of previously created configs into a single one
- Parameters:
configs – Input configs
list_merge_mode – Behavior for merging lists REPLACE: Replaces the target list with the new one (default) EXTEND: Extends the target list with the new one EXTEND_UNIQUE: Extends the target list items with items not present in it hint: use from omegaconf import ListMergeMode to access the merge mode
- Returns:
the merged config object.
- static missing_keys(cfg: Any, *, resolve_custom_resolvers: bool = False) Set[str][source]¶
Returns a set of missing keys in a dotlist style.
Node interpolations that dereference missing values are reported as missing keys, whether they are the full value or part of a string.
- Parameters:
cfg – An
OmegaConf.Container, or a convertible object viaOmegaConf.create(dict, list, …).resolve_custom_resolvers – If
True, custom resolver interpolations are resolved and reported as missing when they dereference missing values. IfFalse(the default), custom resolver interpolations are not resolved and are not reported as missing keys.
- Returns:
set of strings of the missing keys.
- Raises:
ValueError – On input not representing a config.
- static register_new_resolver(name: str, resolver: Callable[[...], Any], *, replace: bool = False, use_cache: bool = False) None[source]¶
Register a resolver.
- Parameters:
name – Name of the resolver.
resolver – Callable whose arguments are provided in the interpolation, e.g., with ${foo:x,0,${y.z}} these arguments are respectively “x” (str), 0 (int) and the value of
y.z.replace – If set to
False(default), then aValueErroris raised if an existing resolver has already been registered with the same name. If set toTrue, then the new resolver replaces the previous one. NOTE: The cache on existing config objects is not affected, useOmegaConf.clear_cache(cfg)to clear it.use_cache – Whether the resolver’s outputs should be cached. The cache is based only on the string literals representing the resolver arguments, e.g., ${foo:${bar}} will always return the same value regardless of the value of
barif the cache is enabled forfoo.
- static resolve(cfg: Container) None[source]¶
Resolves all interpolations in the given config object in-place.
This function works correctly for configs that use only node interpolations (
${key}) with no custom resolvers. When custom resolvers are involved, results may depend on the depth-first, key insertion order traversal, because custom resolvers can do anything — they may be stateful, have side effects, or return different values on each call — and this function has no way to account for that.- Parameters:
cfg – An OmegaConf container (DictConfig or ListConfig).
- Raises:
ValueError – If the input object is not an OmegaConf container.
- static save(config: Any, f: str | Path | IO[Any], resolve: bool = False) None[source]¶
Save as configuration object to a file
- Parameters:
config – omegaconf.Config object (DictConfig or ListConfig).
f – filename or file object
resolve – True to save a resolved config (defaults to False)
- static select(cfg: Container, key: str, *, default: Any = _DEFAULT_MARKER_, throw_on_resolution_failure: bool = True, throw_on_missing: bool = False) Any[source]¶
Select a value from a config using a key path.
The key path uses dot notation (
"a.b.c") or bracket notation ("a[b][c]"), or a mix of both.Keys containing special characters (
.,[,],=) can be expressed by escaping them with a backslash:r"a\.b"— selects the key"a.b"(single key with a literal dot)r"a\[0\]"— selects the key"a[0]"r"a\=b"— selects the key"a=b"
A backslash before any other character passes through unchanged (
r"a\b"selects the key"a\\b"— a backslash followed byb).- Parameters:
cfg – Config node to select from
key – Key path to select (dot/bracket notation, backslash-escapable)
default – Default value to return if key is not found
throw_on_resolution_failure – Raise an exception if an interpolation resolution error occurs, otherwise return None
throw_on_missing – Raise an exception if an attempt to select a missing key (with the value ‘???’) is made, otherwise return None
- Returns:
selected value or None if not found.
- static set_cache(conf: BaseContainer, cache: Dict[str, Any]) None[source]¶
Replace the resolver cache for
confwith a deep copy ofcache.- Parameters:
conf – An OmegaConf container.
cache – New cache dict to install (will be deep-copied).
- static set_readonly(conf: Node, value: bool | None) None[source]¶
Set the read-only flag on
conf.- Parameters:
conf – An OmegaConf node.
value –
Trueto make read-only,Falseto make writable,Noneto inherit from the parent.
- static set_struct(conf: Container, value: bool | None) None[source]¶
Set the struct flag on
conf.When struct mode is enabled, accessing or setting keys that do not exist in the config raises an exception.
- Parameters:
conf – An OmegaConf container.
value –
Trueto enable struct mode,Falseto disable it,Noneto inherit from the parent.
- static structured(obj: Any, parent: BaseContainer | None = None, flags: Dict[str, bool] | None = None, *, max_yaml_expanded_nodes: int | None = 10000) Any[source]¶
Alias for
OmegaConf.create(obj). Accepts any input thatcreateaccepts, though intended for structured config objects (dataclass or attrs types/instances).- Parameters:
obj – Source object — typically a dataclass or attrs type or instance, but any value accepted by
OmegaConf.createis valid.parent – Optional parent node.
flags – Optional flags dict (e.g.
{"readonly": True}).max_yaml_expanded_nodes – Maximum YAML nodes after alias expansion when
objis a YAML string. By default, OmegaConf uses theOMEGACONF_MAX_YAML_EXPANDED_NODESenvironment variable if set, otherwise10_000. Explicit arguments override the environment. PassNoneonly for trusted input. See https://omegaconf.readthedocs.io/en/latest/yaml_aliases.html.
- Returns:
A
DictConfig,ListConfig, orNone(whenobjisNone).
- static to_container(cfg: Any, *, resolve: bool = False, throw_on_missing: bool = False, enum_to_str: bool = False, structured_config_mode: SCMode = SCMode.DICT) Dict[str | bytes | int | Enum | float | bool, Any] | List[Any] | None | str | Any[source]¶
Recursively converts an OmegaConf config to a primitive container (dict or list).
- Parameters:
cfg – the config to convert
resolve – True to resolve all values
throw_on_missing – When True, raise MissingMandatoryValue if any missing values are present. When False (the default), replace missing values with the string “???” in the output container.
enum_to_str – True to convert Enum keys and values to strings
structured_config_mode –
- Specify how Structured Configs (DictConfigs backed by a dataclass) are handled.
By default (
structured_config_mode=SCMode.DICT) structured configs are converted to plain dicts.If
structured_config_mode=SCMode.DICT_CONFIG, structured config nodes will remain as DictConfig.If
structured_config_mode=SCMode.INSTANTIATE, this function will instantiate structured configs (DictConfigs backed by a dataclass), by creating an instance of the underlying dataclass.
See also OmegaConf.to_object.
- Returns:
A dict or a list representing this config as a primitive container.
- static to_object(cfg: Any) Dict[str | bytes | int | Enum | float | bool, Any] | List[Any] | None | str | Any[source]¶
Recursively converts an OmegaConf config to a primitive container (dict or list). Any DictConfig objects backed by dataclasses or attrs classes are instantiated as instances of those backing classes.
- This is an alias for OmegaConf.to_container(…, resolve=True, throw_on_missing=True,
structured_config_mode=SCMode.INSTANTIATE)
- Parameters:
cfg – the config to convert
- Returns:
A dict or a list or dataclass representing this config.
- static to_yaml(cfg: Any, *, resolve: bool = False, sort_keys: bool = False, default_flow_style: bool | None = False) str[source]¶
returns a yaml dump of this config object.
- Parameters:
cfg – Config object, Structured Config type or instance
resolve – if True, will return a string with the interpolations resolved, otherwise interpolations are preserved
sort_keys – If True, will print dict keys in sorted order. default False.
default_flow_style – PyYAML default_flow_style setting. default False.
- Returns:
A string containing the yaml representation.
- static typed_dict(content: Dict[Any, Any] | None = None, key_type: Any = typing.Any, element_type: Any = typing.Any) DictConfig[source]¶
Create a DictConfig with explicit key and value types.
Useful for disambiguating assignment to a Union[Dict[str, X], Dict[str, Y]] field when the value is empty or otherwise matches multiple candidates.
- static typed_list(content: List[Any] | None = None, element_type: Any = typing.Any) ListConfig[source]¶
Create a ListConfig with an explicit element type.
Useful for disambiguating assignment to a Union[List[X], List[Y]] field when the value is empty or otherwise matches multiple candidates.
- static unsafe_merge(*configs: DictConfig | ListConfig | Dict[str | bytes | int | Enum | float | bool, Any] | List[Any] | Tuple[Any, ...] | Any, list_merge_mode: ListMergeMode = ListMergeMode.REPLACE) ListConfig | DictConfig[source]¶
Merge a list of previously created configs into a single one This is much faster than OmegaConf.merge() as the input configs are not copied. However, the input configs must not be used after this operation as will become inconsistent.
- Parameters:
configs – Input configs
list_merge_mode – Behavior for merging lists REPLACE: Replaces the target list with the new one (default) EXTEND: Extends the target list with the new one EXTEND_UNIQUE: Extends the target list items with items not present in it hint: use from omegaconf import ListMergeMode to access the merge mode
- Returns:
the merged config object.
- static update(cfg: Container, key: str, value: Any | None = None, *, merge: bool = True, force_add: bool = False) None[source]¶
Update a value in a config using a key path.
The key path uses dot notation (
"a.b.c") or bracket notation ("a[b][c]"), or a mix of both.Keys containing special characters (
.,[,],=) can be expressed by escaping them with a backslash:r"a\.b"— targets the key"a.b"(single key with a literal dot)r"a\[0\]"— targets the key"a[0]"r"a\=b"— targets the key"a=b"
- Parameters:
cfg – input config to update
key – key path to update (dot/bracket notation, backslash-escapable)
value – value to set, if value if a list or a dict it will be merged or set depending on merge_config_values
merge – If value is a dict or a list, True (default) to merge into the destination, False to replace the destination.
force_add – insert the entire path regardless of Struct flag or Structured Config nodes.
Utility functions importable from the omegaconf module¶
- omegaconf.II() Any¶
Equivalent to
${interpolation}- Parameters:
interpolation
- Returns:
input
${node}with type Any
- omegaconf.SI() Any¶
Use this for String interpolation, for example
"http://${host}:${port}"- Parameters:
interpolation – interpolation string
- Returns:
input interpolation with type
Any
- omegaconf.flag_override(names: List[str] | str, values: List[bool | None] | bool | None) Generator[Node, None, None]¶
Context manager that temporarily overrides one or more flags on
config.The original flag values are restored on exit, even if an exception is raised.
- Parameters:
config – An OmegaConf node whose flags will be overridden.
names – Flag name or list of flag names (e.g.
"readonly","struct").values – New value or list of values corresponding to
names.
- Returns:
Yields
configwith the overridden flags.
- omegaconf.open_dict() Generator[Container, None, None]¶
Context manager that temporarily disables struct mode on
config.While active, new keys can be added freely. The original struct state is restored on exit, even if an exception is raised.
- Parameters:
config – An OmegaConf container.
- Returns:
Yields
configwith struct mode disabled.
- omegaconf.read_write() Generator[Node, None, None]¶
Context manager that temporarily makes
configwritable.The original read-only state is restored on exit, even if an exception is raised.
- Parameters:
config – An OmegaConf node.
- Returns:
Yields
configin a writable state.
- omegaconf.MISSING¶
alias of ???