Comfortable Access to Config Options in Python

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s