Search code examples
python-2.7intdefault-valueconfigparser

ConfigParser use default with int values


I'm trying use ConfigParser with setting of some default values. I know how to set those default values but having trouble with integers.

Here is my code:

import ConfigParser

defaults = {
    "str1": "val1",
    "str2": "val2",
    "int1": 10,
    "int2": 20
   }

section = "some_section"

config = ConfigParser(defaults)

print config.get(section, "str1")
print config.get(section, "str1")
print config.getint(section, "int1")
print config.getint(section, "int2")

The default values works fine when some of the string values are not being provided. But, when some of the integers values are not provided and the default value need to be used, exception of TypeError: argument of type 'int' is not iterable being thrown

I didn't found any example of integers as default values. Any help?


Solution

  • So, during my tests I found some interesting stuff. One of them is that default value for integers and booleans need to be set as strings in the default dictionary (except for None values):

    defaults = {
        "str1": "val1",
        "str2": "val2",
        "int1": "10",
        "int2": "20",
        "boolean1": "True",
        "boolean2": "False",
        "empty_var": None
    }
    

    Note: to extract booleans use ConfigParser.getboolean

    Now it works ;)