coma.hooks.config_hook¶
Config hook utilities and factories.
- OverrideProtocolOrSentinels¶
Callable to override config attributes with command line arguments, or
SENTINELto useOverridewith default parameters, orNoneto disable overriding altogether.Alias:
alias of
OverrideProtocol|GeneralSentinel|None
- initialize_factory(config_id: str, raise_on_fnf: bool = False) Callable[[T], T | None][source]¶
Factory for creating an invocation hook with
config_hooksemantics.Specifically, initializes the
Configcorresponding toconfig_idfrom amongst the configs (or supplemental configs) incoma.hooks.base.HookData.parameters.The initialization leverages
initialize(). Thefile_pathparameter toinitialize()is derived by callingget_file_path()on the current value of thepersistence_managerobject, except ifconfig_idcorresponds to a config whereis_serializable()isFalse, which is never initialized from file.If loading from file fails due to a
FileNotFoundError, the error is re-raised ifraise_on_fnfisTrue. Ifraise_on_fnfisFalse, a config with default values is initialized and the missing file is silently ignored.Example
Fail fast when encountering a
FileNotFoundError:coma.command(..., config_hook=initialize_factory(..., raise_on_fnf=True))
- Parameters:
config_id (
ConfigID) – The identifier of the config to initialize.raise_on_fnf (bool) – If
True, raises aFileNotFoundErrorif the config file was not found. IfFalse, a config object with default values is initialized instead of failing outright.
- Returns:
A hook with partial
config_hooksemantics.- Return type:
- Raises:
KeyError – If
config_iddoes not match any known config or supplemental config.FileNotFoundError – If
raise_on_fnfisTrueand the config file was not found.Others – As may be raised by the underlying
omegaconfhandler or byinitialize().
- write_factory(config_id: str, *, instance_key: str | None = None, resolve: bool = False, overwrite: bool = False) Callable[[T], T | None][source]¶
Factory for creating an invocation hook with partial
config_hooksemantics.Specifically, serializes the
instance_keyinstance of theConfigcorresponding toconfig_idfrom amongst the configs (or supplemental configs) incoma.hooks.base.HookData.parameters.The serialization leverages
write(), withinstance_keyandresolvepassed directly to it. Thefile_pathparameter towrite()is derived by callingget_file_path()on the current value of thepersistence_managerobject, except ifconfig_idcorresponds to a config whereis_serializable()isFalse, which is never written to file.If the destination file already exists, new content is only written if
overwriteisTrue.Example
Always write a specific config instance, rather than the latest:
coma.command(..., config_hook=write_factory(..., instance_key="MY KEY"))
- Parameters:
config_id (
ConfigID) – The identifier of the config to serialize.instance_key (
InstanceKey, optional) – The specificConfiginstance to serialize. IfNone, the latest instance is used.overwrite (bool) – Whether to overwrite the file content whe the destination file already exists.
- Returns:
A hook with partial
config_hooksemantics.- Return type:
- Raises:
- override_factory(config_id: str, instance_key: str | None = None, override: OverrideProtocol | GeneralSentinel | None = GeneralSentinel.token) Callable[[T], T | None][source]¶
Factory for creating an invocation hook with partial
config_hooksemantics.Specifically, overrides the
instance_keyinstance of theConfigcorresponding toconfig_idfrom amongst the configs (or supplemental configs) incoma.hooks.base.HookData.parameterswith command line arguments.Leverages
Override, withinstance_keypassed directly to it. Ifoverridehas valueSENTINEL, anOverridewith default parameters is used. Slight variations can be declared by directly settingoverrideto a specific instance ofOverride. Alternatively, entirely custom implementations can also be provided so long as the provided object is a Callable with a signature that adheres to theOverrideProtocol. IfoverrideisNone, returns immediately without performing any override.Example
Change separator to
"~":coma.command(..., config_hook=override_factory(..., override=Override(sep="~")))
- Parameters:
config_id (
ConfigID) – The identifier of the config to override.instance_key (
InstanceKey, optional) – The specificConfiginstance to override. IfNone, the latest instance is used.override (
OverrideProtocolOrSentinels) – Callable to override config attributes with command line arguments; orSENTINELto useOverridewith default parameters; orNoneto disable override altogether.
- Raises:
KeyError – If
config_iddoes not match any known config or supplemental config.Others – As may be raised by the underlying
omegaconfhandler or byoverride.
- Returns:
A hook with partial
config_hooksemantics.- Return type:
- default_factory(*config_ids: str, raise_on_fnf: bool = False, override_instance_key: str | None = None, override: OverrideProtocol | GeneralSentinel | None = GeneralSentinel.token, skip_write: Container[str] | None = None, write: bool = True, write_instance_key: str | None = 'BASE', resolve: bool = False, overwrite: bool = False) Callable[[T], T | None][source]¶
Factory for creating an invocation hook with
config_hooksemantics.Note
If
config_idsis empty, defaults to all registered configs for the command being executed. In other words, only specifyconfig_idsexplicitly to limit the factory to only those configs.Assumptions made in designing this config hook implementation:
- Configs are declarative. They follow the following declaration hierarchy:
CLI override > file (if any) > code default.
- Configs are, by default, useful.
This means, by default, declared configs (both standard and supplemental) are loaded (where “loaded” here means loaded based on the entire declarative hierarchy). However, the CLI override can be disabled by setting
overridetoNone.
- Persistence of configs is typically desirable.
This means that, by default, configs are serialized (to enable the middle of the declarative hierarchy), but skipping serialization is made easy (use
skip_writeto disable for particular configs, or setwriteisFalseto disable for all configs).
- Configs often fall into neat groups that should be treated a particular way.
For example, one group skips overriding, while another skips serializing. Both
config_idsandskip_writeenable such group declarations.
This default factory is equivalent to:
1. Calling
initialize_factory()on the specified configs, passing inraise_on_fnfdirectly.2. Then, calling
override_factory(), passing inoverride_instance_key, andoverridedirectly.3. Then, only if
writeisTrue, callingwrite_factory()on all specified configs not also inskip_write, passing inwrite_instance_key,resolve, andoverwritedirectly.Example
Override only one group and configs and serialize only another group:
coma.command( ..., config_hook=( default_factory("override", "only", "configs", write=False), default_factory("write", "only", "configs", override=None), ) )
- Parameters:
*config_ids (
ConfigID) – Configs on which to apply the config hook. If empty, do so for all configs registered with the command currently being executed.raise_on_fnf (bool) – Passed directly to
coma.hooks.config_hook.initialize_factory().override_instance_key (
InstanceKey, optional) – Passed directly tocoma.hooks.config_hook.override_factory().override (
OverrideProtocolOrSentinels) – Passed directly tocoma.hooks.config_hook.override_factory().skip_write (typing.Container[
ConfigID], optional) – IfwriteisTrue, skip serialization for each of these configs.write (bool) – Whether to serialize configs.
write_instance_key (
InstanceKey, optional) – Passed directly tocoma.hooks.config_hook.write_factory().resolve (bool) – Passed directly to
coma.hooks.config_hook.write_factory().overwrite (bool) – Passed directly to
coma.hooks.config_hook.write_factory().
- Returns:
A hook with
config_hooksemantics.- Return type:
- Raises:
Various – As may be raised by the underlying components.
- preload(data: InvocationData, *config_ids, limited: bool = False, raise_on_fnf: bool = False, override: OverrideProtocol | GeneralSentinel | None = GeneralSentinel.token) None[source]¶
Convenience wrapper around
coma.hooks.config_hook.default_factory().Configs are declarative. They follow the following declaration hierarchy: CLI override > file (if any) > code default. “Load” here means loading based on the entire declarative hierarchy. “Pre” here refers to the idea that this procedure is typically called in a user-defined
pre_config_hookto load some configs (typically supplemental configs) as a preprocessing step before the mainconfig_hook.Preloading never serializes any of the configs. CLI is enabled by default, but can be disabled by setting
overridetoNone. IflimitedisTrue, limit override exclusivity checks to just theconfig_ids. Otherwise, perform exclusivity checks on all configs indata.parameters(which requires initializing all configs).Example
Preload some supplemental configs in
pre_config_hook:def pre_config_hook(data: InvocationData) -> InvocationData: preload_ids = ["supplemental_cfg_1", "supplemental_cfg_2"] preload(data, *preload_ids) cfgs = data.parameters.select(*preload_ids) do_something_with(cfgs) # This prevents further processing of these configs. data.parameters.delete(*preload_ids) @command( name="command_name", pre_config_hook=pre_config_hook, ..., supplemental_cfg_1=..., supplemental_cfg_2=..., ) def my_cmd(...): ...
- Parameters:
data (
InvocationData) – Invocation data received as input to whichever invocation hook (typicallypre_config_hook)preload()is being called in.*config_ids (
ConfigID) – Configs to preload. If empty, do so for all configs indata.parameters. Passed directly tocoma.hooks.config_hook.default_factory().limited (bool) – Whether to limit override exclusivity checks to just the
config_idsraise_on_fnf (bool) – Passed directly to
coma.hooks.config_hook.default_factory().override (
OverrideProtocolOrSentinels) – Passed directly tocoma.hooks.config_hook.default_factory().
- Returns:
datais modified in-place and preloaded configs should be retrieved directly from it.- Return type:
None
- Raises:
ValueError – If
limitedisTruebutconfig_idsis empty.Others – As may be raised by
coma.hooks.config_hook.default_factory().