bw2 / ConfigArgParse

A drop-in replacement for argparse that allows options to also be set via config files and/or environment variables.
MIT License
719 stars 121 forks source link

Sections in config file #250

Closed LasseMenzel closed 2 years ago

LasseMenzel commented 2 years ago

I do not go with your design choice Nr 5: 5. don’t force users to put config file settings in the right .ini [sections]. This doesn’t have a clear benefit since all options are command-line settable, and so have a globally unique key anyway. Enforcing sections just makes things harder for the user and adds complexity to the implementation.

Sections make it possible to setup different configurations in one file. I am using Sections in test-environment where several different setups with different configurations are needed. Further i use sections to support different "default" values for linux and windows environments (e.g paths). So, for my usecases sections help me a lot and remove complexity.

Suggestion: Add sections support by argument. E.g. --section "\<section name>"

bw2 commented 2 years ago

If you haven't already, you might be able to solve this by creating your own subclass of ConfigFileParser.

tristanlatr commented 2 years ago

Hello @LasseMenzel , @bw2,

I've been working on a decoupled way of supporting INI sections as well as TOML sections. This open the possibility to use configargparse to integrate into common project files pyproject.tomland setup.cfg, which a very cool feature.

Basically it works like this:

>>> TomlParser = TomlConfigParser(['tool.my_super_tool']) # Simple TOML parser.
>>> parser = ArgumentParser(..., default_config_files=['./pyproject.toml'], config_file_parser_class=TomlParser)

or you can create a parser that support both TOML and INI:

>>> MY_CONFIG_SECTIONS = ['tool.my_super_tool', 'tool:my_super_tool', 'my_super_tool']
>>> TomlParser =  TomlConfigParser(MY_CONFIG_SECTIONS)
>>> IniParser = IniConfigParser(MY_CONFIG_SECTIONS, split_ml_text_to_list=True)
>>> MixedParser = CompositeConfigParser([TomlParser, IniParser]) # This parser supports both TOML and INI formats.
>>> parser = ArgumentParser(..., default_config_files=['./pyproject.toml', 'setup.cfg', 'my_super_tool.ini'], config_file_parser_class=MixedParser)

Go here for more documentation: https://pydoctor.readthedocs.io/en/latest/api/pydoctor._configparser.html

And here's the code: https://github.com/twisted/pydoctor/blob/master/pydoctor/_configparser.py (please feel free to use it, it can be copied an used as is)

But still, I think it would be worth it to officially adding this feature to configargparse since this kind of integration are becoming a real use case scenarios for many projects.

Tell me what you think,