Python config parser that supports section inheritance?

Maascamp picture Maascamp · Jun 30, 2011 · Viewed 9.2k times · Source

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?

Answer

tuomur picture tuomur · Jun 30, 2011

Python's ConfigParser can load multiple files. Files read later on can override settings from the first file.

For example, my application has database settings in its internal default configuration file:

[database]
server = 127.0.0.1
port = 1234
...

I override these on a different server with a "environment.ini" file containing the same section but different values:

[database]
server = 192.168.0.12
port = 2345
...

In Python:

import os
from ConfigParser import ConfigParser
dbconf = ConfigParser()
dbconf.readfp(open('default.ini'))
if os.path.exists('environment.ini'):
    dbconf.readfp(open('environment.ini'))
dbconf.get('database', 'server') # Returns 192.168.0.12