4

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.

Rusty Lemur
  • 1,697
  • 1
  • 21
  • 54
  • If the parameter is not present in the configuration file, will the attempted assignment result in the variable being unset? I'm not at my computer, so can't test right now. – Rusty Lemur Feb 28 '19 at 01:46

2 Answers2

8

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')
L0ngSh0t
  • 361
  • 2
  • 9
  • I'm keeping this marked as the answer since it was submitted a little before the other one with the same solution. However, I found just now that it is not supported in 2.7. Are there other options for 2.7? – Rusty Lemur May 06 '19 at 19:30
  • Is there a way to have fallback values when loading from JSON files? Didn't see anything in the docs yet https://docs.python.org/3/library/configparser.html#fallback-values – Nav Jun 21 '23 at 12:53
1

https://docs.python.org/3/library/configparser.html#fallback-values

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):
        try:
            configs = ConfigParser.ConfigParser()
            configs.read(configFile)
            listen_address = configs.get('ServerConfigs', 'listen_address', fallback=listen_address)
            listen_port = configs.get('ServerConfigs', 'listen_port', fallback=listen_port)
        except configparser.Error:
            # do whatever u want
            pass

jayprakashstar
  • 395
  • 2
  • 12