Computer Science Canada

What is the best way to get values from a config file?

Author:  BigBear [ Mon Feb 04, 2013 10:58 am ]
Post subject:  What is the best way to get values from a config file?

I have 15 values that I want to get from a config file and store them in separate variables.

I am using

from ConfigParser import SafeConfigParser

parser = SafeConfigParser()
parser.read(configFile)

and it is a really good library.



Option #1
If I change the name of the variable and want it to match the config file entry I have to edit the corresponding line in the function
Python:

def fromConfig():
    #open file
    localOne = parser.get(section, 'one')
    localTwo = parser.get(section, 'two')
    return one, two

one = ''
two = ''
#etc
one, two = fromConfig()



Option #2
It is cleaner to see where the variables get their values from, but then I would be opening and closing the file for every variable
Python:

def getValueFromConfigFile(option):
    #open file
    value = parser.get(section, option)
    return value

one = getValueFromConfigFile("one")
two = getValueFromConfigFile("two")


Option #3
This one doesn't make much sense since I have to have another list of all my variable names, but the function is cleaner.
Python:

def getValuesFromConfigFile(options):
    #open file
    values = []
    for option in options:
        values.append(parser.get(section, option))

    return values

one = ''
two = ''
configList = ["one", "two"]
one, two = getValuesFromConfigFile(configList)


: