Booleans in ConfigParser always return True

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. What for? It must be False since some_other_boolean set to no .

+6
source share
2 answers

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 that forces an option in a specified section to a boolean value. Please 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 force it to return False. These string values ​​are case-insensitive. Any other value will raise a ValueError.

The bool() constructor converts an empty string to False. Non-empty lines are True. bool() does nothing special for "false", "no", etc.

 >>> bool('false') True >>> bool('no') True >>> bool('0') True >>> bool('') False 
+18
source

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

+1
source

Source: https://habr.com/ru/post/927046/


All Articles