1
nodes:
  node1: 1
  node2: 2
  node3: 3

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

我可以制作一个subfield解析器来返回nodes["node1"]并存储它selected_node吗?

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

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

2 回答 2

2
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
于 2022-02-09T02:50:38.450 回答
0

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

最好避免导入私有接口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
于 2022-02-08T20:30:10.950 回答