ConfigArgParse
ConfigArgParse copied to clipboard
Allow nested YAML properties
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?
See also implementation in https://github.com/kampka/yconf
Sure, a PR would be appreciated.
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 @dataclass
es, 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
)