37

This is my example script:

import ConfigParser

config = ConfigParser.ConfigParser()
config.read('conf.ini')

print bool(config.get('main', 'some_boolean'))
print bool(config.get('main', 'some_other_boolean'))

And this is conf.ini:

[main]
some_boolean: yes
some_other_boolean: no

When running the script, it prints True twice. Why? It should be False, as some_other_boolean is set to no.

user1447941
  • 3,675
  • 10
  • 29
  • 34

3 Answers3

67

Use getboolean():

print config.getboolean('main', 'some_boolean') 
print config.getboolean('main', 'some_other_boolean')

From the Python manual:

RawConfigParser.getboolean(section, option)

A convenience method which coerces the option in the specified section to a Boolean value. Note that the accepted values for the option are "1", "yes", "true", and "on", which cause this method to return True, and "0", "no", "false", and "off", which cause it to return False. These string values are checked in a case-insensitive manner. Any other value will cause it to raise ValueError.

Such as:

my_bool = config.getboolean('SECTION','IDENTIFIER')

The bool() constructor converts an empty string to False. Non-empty strings are True. bool() doesn't do anything special for "false", "no", etc.

>>> bool('false')
True
>>> bool('no')
True
>>> bool('0')
True
>>> bool('')
False
ruhsuzbaykus
  • 13,240
  • 2
  • 20
  • 21
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
2

It returns the string "no". bool("no") is True

James Thiele
  • 393
  • 3
  • 9
0

I had the same issue, I tried to iterate over all arg values and see if they are boolean. However, args are namespace object and are not iterable. So I had to get an instance of iterable and then after modifying to bool arguments, I revert it back to a namespace object as follows:

updated_args = {}
for key, value in vars(args).items():
    if isinstance(value, str) and value.lower() in ['true', 'false']:
        updated_args[key] = value.lower() == 'true'
    else:
        updated_args[key] = value

args = argparse.Namespace(**updated_args)