Introduction: ConfigReader#
from pprint import pprint
from dicfg import ConfigReader
The first step is to create a configs folder containing a main config file: config.yml.#
!cat ./configs/config.yml
default:
config_int: 1
config_string: "fire"
config_list: [1, 2, 3]
config_none: None
config_dict:
sub_config: "water"
The second step is to create a ConfigReader object.#
# A name should be set, which will be used later as a reference in user configs and command line interface.
config_reader = ConfigReader(name="myconfig")
The main config file can be read with the .read method of the ConfigReader class.#
# ConfigReader will automatically read from .configs/config.
# However you can change this by setting a different main_config_path when initializing ConfigReader
pprint(config_reader.read(), sort_dicts=False)
{'default': {'config_int': 1,
'config_string': 'fire',
'config_list': [1, 2, 3],
'config_none': 'None',
'config_dict': {'sub_config': 'water'}}}
The main config can be updated with a user config dictionary.#
# Note the 'myconfig' key in the 'user_config',
# which corresponds to the name given when initializing ConfigReader
user_config = {"myconfig": {"default": {"config_int": 2}}}
pprint(config_reader.read(user_config), sort_dicts=False)
{'default': {'config_int': 2,
'config_string': 'fire',
'config_list': [1, 2, 3],
'config_none': 'None',
'config_dict': {'sub_config': 'water'}}}
The main config can be updated with a user config file (.yml, .yaml, .json).#
!cat ./user_config.yml
myconfig:
default:
config_int: 3
user_config = "./user_config.yml"
pprint(config_reader.read(user_config), sort_dicts=False)
{'default': {'config_int': 3,
'config_string': 'fire',
'config_list': [1, 2, 3],
'config_none': 'None',
'config_dict': {'sub_config': 'water'}}}