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

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

Can I make a subfield resolver that returns nodes["node1"] and stores it in selected_node?

My attempts so far result in this error:

omegaconf.errors.GrammarParseError: token recognition error at: '{'
    full_key: selected_node
    object_type=dict
Michael Litvin
  • 3,976
  • 1
  • 34
  • 40

2 Answers2

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
Omry Yadan
  • 31,280
  • 18
  • 64
  • 87
0

I managed to solve this using the implementation below.

It would be better to avoid importing the private interface omegaconf._impl, but I haven't yet found a way to do that.

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
Michael Litvin
  • 3,976
  • 1
  • 34
  • 40