Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Why? It should be False, as some_other_boolean is set to no.

like image 831
user1447941 Avatar asked Oct 05 '12 16:10

user1447941


People also ask

What is Configparser Configparser ()?

ConfigParser is a Python class which implements a basic configuration language for Python programs. It provides a structure similar to Microsoft Windows INI files. ConfigParser allows to write Python programs which can be customized by end users easily.

What is Configparser module in Python?

The configparser module from Python's standard library defines functionality for reading and writing configuration files as used by Microsoft Windows OS. Such files usually have . INI extension. The INI file consists of sections, each led by a [section] header. Between square brackets, we can put the section's name.

What is config () in Python?

A Python configuration file is a pure Python file that populates a configuration object. This configuration object is a Config instance. While in a configuration file, to get a reference to this object, simply call the get_config() function, which is available in the global namespace of the script.

Is Configparser built in Python?

configparser comes from Python 3 and as such it works well with Unicode. The library is generally cleaned up in terms of internal data storage and reading/writing files.


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 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.

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
like image 151
John Kugelman Avatar answered Sep 29 '22 23:09

John Kugelman


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

like image 30
James Thiele Avatar answered Sep 29 '22 23:09

James Thiele