Initialising a Config class

Loris Bennett loris.bennett at fu-berlin.de
Tue Apr 11 10:29:58 EDT 2023


Hi,

Having solved my problem regarding setting up 'logger' such that it is
accessible throughout my program (thanks to the help on this list), I
now have problem related to a slightly similar issue.

My reading suggests that setting up a module with a Config class which
can be imported by any part of the program might be a reasonable approach:


import configparser

class Config:

    def __init__(self, config_file):

        config = configparser.ConfigParser()
        config.read(config_file)
  

However, in my config file I am using sections, so 'config' is a dict of
dicts.  Is there any cleverer generic way of initialising the class than


        self.config = config


?

This seems a bit clunky, because I'll end up with something like


   import config
   ...
   c = config.Config(config_file)
   uids = get_uids(int(c.config["uids"]["minimum_uid"]))


rather than something like, maybe


   uids = get_uids(int(c.minimum_uid))


or


   uids = get_uids(int(c.uids_minimum_uid))


So the question is: How can I map a dict of dicts onto class attributes
in a generic way such that only code which wants to use a new
configuration parameter needs to be changed and not the Config class
itself?  Or should I be doing this differently?

Note that the values from ConfigParser are all strings, so I am fine
with the attributes being strings - I'll just convert them as needed at
the point of use (but maybe there is also a better way of handling that
within a class).
 
Cheers,

Loris

-- 
This signature is currently under constuction.


More information about the Python-list mailing list