Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] Convert to dict #19

Open
re-young opened this issue Apr 17, 2019 · 4 comments
Open

[Feature Request] Convert to dict #19

re-young opened this issue Apr 17, 2019 · 4 comments

Comments

@re-young
Copy link

Hey,

It would be great to have the native ablilty to convert config into a dict.

def convert_to_dict(cfg_node, key_list):

@DKandrew
Copy link

A follow up to this question, can we use CfgNode like dict? i.e. cfg['key'] can return the value of the key.

@DKandrew
Copy link

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

@tekinengin
Copy link

For non-nested cfgNodes you can cast it into dict -> (dict)(your_cfgNode). Otherwise you need to do it recursively.

@mitchism
Copy link

Two points:

  1. 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)

  2. 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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants