Search code examples
pythoniniconfigparser

How to parse boolean with config parser


Using python's builtin configparser, I want to parse boolean values in my conf file.

Example:

[SECTION]
foo = False

However, when accessing the variable I notice that it is processed as a string.

>>> config['SECTION']['foo']
'False'

Furthermore, when I attempt to correct this behavior and reassign key foo to it's proper boolean representative, I get this error

>>>         if config['SECTION']['foo'] == 'True':
...             config['SECTION']['foo'] = True
...         elif config['SECTION']['foo'] == 'False':                                                                                                                                      
...             config['SECTION']['foo'] = False
...         else:                                    
...             Exception("foo must be bool")
TypeError: option values must be strings                                                                                                                                                      

Unfortunately, this behavior leads to problematic situations where the following performs unexpectedly

print(config['SECTION']['foo']) # 'False'

if config['SECTION']['foo']:
   print('do things when foo is True') # this runs, but foo actually 
                                       # represents false, but in string form

How am I supposed to deal with booleans when parsing with configparser with the least amount of overhead as possible?


Solution

  • You want to use getboolean, a function on the section object.

    For example

    >>> config['SECTION'].getboolean('foo')
    False
    

    Documentation