ConfigArgParse icon indicating copy to clipboard operation
ConfigArgParse copied to clipboard

Allow nested YAML properties

Open wookayin opened this issue 7 years ago • 3 comments

It would be great if nested YAML properties, where name is delimited by . (which is a common convention used in other YAML-based configurations). Something like:

settings.yaml

simple: 3
foo:
   bar: 1
   baz: "hello"

to allow properties such as foo.bar and foo.baz:

$ python main.py --foo.bar 2

Parsed Arugments:
args['simple'] == 3
args['foo'] : some dict-like objects, such as args['foo']['bar'] == 1 or args['foo'].bar == 1
args['foo']['baz'] == 'hello' 

I think it can be easily achieved by modifying YAMLConfigFileParser, and this is quite useful. How do you think?

wookayin avatar May 24 '17 06:05 wookayin

See also implementation in https://github.com/kampka/yconf

andreas-wilm avatar Jul 06 '17 05:07 andreas-wilm

Sure, a PR would be appreciated.

bw2 avatar Dec 26 '17 19:12 bw2

I've been thinking about doing something like this. I think this is trickier than it seems. For instance, how would you specify the "type" of the nested fields?

What I've done instead is create Python @dataclasses, with a .from_yaml() classmethod/constructor. (I have specified this in a mixin, since it can easily be reused. Something like this:

class _FromYAMLMixin:
    """Mixin that adds a from_yaml constructor."""

    @classmethod
    def from_yaml(cls, in_string):
        """Alternative constructor, takes YAML (or JSON) string."""
        in_dict = yaml.safe_load(in_string)
        return cls(**in_dict)


@dataclass
class NetworkConfig(_FromYAMLMixin):
    """Class that holds network configuration."""

    required: bool = False
    host: str = None
    port: int = 1883

and then

    parser.add_argument(
        "--nwk-conf", default="{}", type=NetworkConfig.from_yaml
    )

ukrutt avatar Jan 23 '20 13:01 ukrutt