Python config parser that supports section inheritance?

Viewed 10480

I'm looking for an ini style config parser in Python that supports section inheritance similar to what Zend_Config_Ini does in PHP.

Does such a module exist or will I need to roll my own?

3 Answers

Here's what I used. extended_get method is what you need - it supports hierarchical sections.

import re
import io
import ConfigParser

class ZendConfigParser(ConfigParser.ConfigParser):
    def extended_get(self, section, key):
        if self.has_option(section, key):
            return self.get(section, key)
        else:
            orig_section, parent_section = self._get_orig_section(section)
            if orig_section != None:
                if self.has_option(orig_section,key):
                    return self.get(orig_section,key)
                else:
                    return self.extended_get(parent_section,key)
            else:
                return None



    def _get_orig_section(self, zend_section):
        orig_section = None
        parent_section = None
        for section in self.sections():
            if re.search(r'^[ \t]*' + zend_section + '\\b', section) != None:
                orig_section = section
                #look for a parent section
                match = re.match(r'\w+[ \t]*:[ \t]*(\w+)$', section)
                if match != None:
                    parent_section = match.groups()[0]
                break

        return (orig_section, parent_section)

config = ZendConfigParser()
config.read(file)
print(config.extended_get('production', 'database.params.host'))
Related