omegaconf

Custom resolver to select a field from a DictConfig


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

Solution

  • 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