"""Implementation of a dictionary backing configuration."""from__future__importannotations__author__='Paul Landes'fromtypingimportDict,Set,Type,AnyimportloggingfromcollectionsimportOrderedDictfrom.importConfigurableError,Configurable,TreeConfigurable,Dictablelogger=logging.getLogger(__name__)
[docs]classDictionaryConfig(TreeConfigurable,Dictable):"""This is a simple implementation of a dictionary backing configuration. The provided configuration is just a two level dictionary. The top level keys are the section and the values are a single depth dictionary with string keys and values. You can override :meth:`_get_config` to restructure the dictionary for application specific use cases. One such example is :meth:`.JsonConfig._get_config`. .. document private functions .. automethod:: _get_config """
[docs]def__init__(self,config:Dict[str,Dict[str,Any]]=None,default_section:str=None,deep:bool=False):"""Initialize. :param config: configures this instance (see class docs) :param default_section: used as the default section when non given on the get methds such as :meth:`get_option` """super().__init__(default_section=default_section)ifconfigisNone:self._dict_config={}else:self._dict_config=configself._deep=deepself.invalidate()
[docs]@classmethoddeffrom_config(cls:Type,source:Configurable,**kwargs:Dict[str,Any])->DictionaryConfig:"""Create an instance from another configurable. :param source: contains the source data from which to copy :param kwargs: initializer arguments for the new instance :return: a new instance of this class with the data copied from ``source`` """secs:Dict[str,Any]=OrderedDict()params:Dict[str,Any]=dict(kwargs)if'default_section'notinparamsand \
source.default_sectionisnotNone:params['default_section']=source.default_sectionifisinstance(source,DictionaryConfig):params['deep']=source.deepforsecinsorted(source.sections):svs=OrderedDict()secs[sec]=svssource.populate(svs,sec)returncls(secs,**kwargs)
@propertydefsections(self)->Set[str]:"""Return the top level keys of the dictionary as sections (see class doc). """ifself._deep:returnsuper().sectionselse:returnset(self._get_config().keys())@sections.setterdefsections(self,sections:Set[str]):raiseRuntimeError('Can not set sections')