自定义解析器 select 来自 DictConfig 的字段

Custom resolver to select a field from a DictConfig

nodes:
  node1: 1
  node2: 2
  node3: 3

selected_node: ${subfield:${nodes},node1}

我可以制作一个 subfield 解析器 returns nodes["node1"] 并将其存储在 selected_node 中吗?

到目前为止我的尝试导致了这个错误:

omegaconf.errors.GrammarParseError: token recognition error at: '{'
    full_key: selected_node
    object_type=dict

我使用下面的实现设法解决了这个问题。

最好避免导入私有接口 omegaconf._impl,但我还没有找到这样做的方法。

import yaml
from omegaconf import OmegaConf


def _subfield(key, field, _parent_):
    from omegaconf._impl import select_value
    obj = select_value(cfg=_parent_,
                       key=key,
                       absolute_key=True,
                       throw_on_missing=True,
                       throw_on_resolution_failure=True)
    return obj[field]


OmegaConf.register_new_resolver("subfield", _subfield)

d = yaml.safe_load("""
nodes:
  node1: this_one
  node2: not_this
  node3: and_not_this

selected_node: ${subfield:nodes,node1}
""")

cfg = OmegaConf.create(d)
print(cfg.selected_node)
# this_one
from omegaconf import OmegaConf
s = """
nodes:
  node1: 1
  node2: 2
  node3: 3

selected: ${subfield:${nodes},node1}
"""

def _subfield(node, field):
    return node[field]


OmegaConf.register_new_resolver("subfield", _subfield)
a = OmegaConf.create(s)
print(a.selected) # -> 1