Search code examples
pythondefaultconfigparser

Python ConfigParser use defaults if not in configuration file


What's the best way to use a default value if it isn't defined in a configuration file? E.g. in the example below, perhaps only listen_address is defined in the configuration, and listen_port is absent.

I'm trying something like this:

import ConfigParser
from os.path import isfile

if __name__ == "__main__":

    # Set default values
    listen_address = '127.0.0.1'
    listen_port = 8000

    # Check for configurations from file and override defaults
    configFile = './configuration.ini'
    if isfile(configFile):
        configs = ConfigParser.ConfigParser()
        configs.read(configFile)
        try:
            listen_address = configs.get('ServerConfigs', 'listen_address')
        except:
            pass
        try:
            listen_port = configs.get('ServerConfigs', 'listen_port')
        except:
            pass

But that feels ugly.


Solution

  • You could use the built-in fallback parameter found here that is used if it cannot find the option:

    listen_address = configs.get('ServerConfigs', 'listen_address', fallback='127.0.0.1')