您可以通过将 OmegaConf 的变量插值与其自定义解析器相结合来实现此目的。
这是一个ClassA.__init__
同时接收model
和modelconf
作为参数的示例。该参数modelconf
是cfg.model
已_target_
删除其字段的副本。
# conf.yaml
_target_: app.ClassA
foo: bar
model:
_target_: app.ClassB
hello: world
modelconf: "${remove_target: ${.model}}"
# app.py
import hydra
from omegaconf import DictConfig, OmegaConf
class ClassB:
def __init__(self, hello: str):
print(f"ClassB.__init__ got {hello=}")
class ClassA:
def __init__(self, foo: str, model: ClassB, modelconf: DictConfig) -> None:
print(f"ClassA.__init__ got {foo=}, {model=}, {modelconf=}")
def remove_target_impl(conf: DictConfig) -> DictConfig:
"""Return a copy of `conf` with its `_target_` field removed."""
conf = conf.copy()
conf.pop("_target_")
return conf
OmegaConf.register_new_resolver(
"remove_target", resolver=remove_target_impl, replace=True
)
@hydra.main(config_path=".", config_name="conf.yaml")
def main(cfg: DictConfig) -> None:
hydra.utils.instantiate(cfg)
if __name__ == "__main__":
main()
在命令行:
$ python3 app.py
ret = run_job(
ClassB.__init__ got hello='world'
ClassA.__init__ got foo='bar', model=<app.ClassB object at 0x10a125ee0>, modelconf={'hello': 'world'}
删除该_target_
字段的动机modelconf
如下:如果未_target_
删除键,则调用 to将导致映射到(而不是 a )的实例。instantiate
modelconf
ClassB
DictConfig
另请参见 的_convert_
参数instantiate
。使用_convert_=="partial"
or_convert_=="all"
意味着ClassA.__init__
将接收 type 的modelconf
参数dict
而不是 type的参数DictConfig
。
def remove_target_and_add_convert_impl(conf: DictConfig) -> DictConfig:
conf = conf.copy()
conf.pop("_target_")
conf["_convert_"] = "all" # instantiate should now result in a dict rather than in a DictConfig
return conf