Open re-young opened 5 years ago
A follow up to this question, can we use CfgNode like dict? i.e. cfg['key'] can return the value of the key.
Here is my implementation (copied from the config.py)
_VALID_TYPES = {tuple, list, str, int, float, bool}
def convert_to_dict(cfg_node, key_list=[]):
""" Convert a config node to dictionary """
if not isinstance(cfg_node, CfgNode):
if type(cfg_node) not in _VALID_TYPES:
print("Key {} with value {} is not a valid type; valid types: {}".format(
".".join(key_list), type(cfg_node), _VALID_TYPES), )
return cfg_node
else:
cfg_dict = dict(cfg_node)
for k, v in cfg_dict.items():
cfg_dict[k] = convert_to_dict(v, key_list + [k])
return cfg_dict
For non-nested cfgNodes you can cast it into dict -> (dict)(your_cfgNode)
. Otherwise you need to do it recursively.
Two points:
Simplest option: If you only wanted a native python dictionary, you could simply use the yaml package instead of yacs (or instantiate two copies of the config: first a CfgNode returned by yacs... second as a dict returned by yaml). Just load your .YML file like:
import yaml
my_config_dict = yaml.load(open('/my_project/my_config.yml'), Loader=yaml.FullLoader)
Alternatively: Don't make any changes, just load your yacs CfgNode like normal, since the config object can be accessed either (a.) via Object-instance syntax, or (b.) via dict-key syntax. If you treat your yacs config as a dict, it should be operationally equivalent (exceptif your code uses type-checks! That's the one hiccup I can think of so far)
Hey,
It would be great to have the native ablilty to convert config into a dict.
https://github.com/rbgirshick/yacs/blob/8a679b445174e4c284858732b485a5a2fa678058/yacs/config.py#L191