Comfortable Access to Config Options in Python

12. October, 2012

I always felt that Python’s ConfigParser API could be better. I like to access my config options like this:

    self.config.option

To solve this, I wrote ConfigProvider which can copy options from ConfigParser into a Python instance:

class ConfigProvider:
    __doc__ = 'Interface which can copy values from ConfigParser into a config object'
    
    def __init__(self, cfg):
        self.cfg = cfg
    
    def update(self, section, cfg):
        __doc__ = 'Updates values in cfg with values from ConfigParser'
        
        for name, value in inspect.getmembers(cfg):
            if name[0:2] == '__' or inspect.ismethod(value):
                continue
            
            #print name
            if self.cfg.has_option(section, name):
                setattr(cfg, name, self.cfg.get(section, name))

The magic happens in update() which examines the config object that you pass in and which copies the values from the external ConfigParser into it.

The gist “Comfortable config access with Python” contains the whole code and a demo.


%d bloggers like this: