5

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.

1
  • 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. Commented Feb 28, 2019 at 1:46

2 Answers 2

10

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')
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Is there a way to have fallback values when loading from JSON files? Didn't see anything in the docs yet docs.python.org/3/library/configparser.html#fallback-values
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.