flutefreak7 flutefreak7 - 5 months ago 21
Python Question

Why does ConfigParser items() give raw strings while get() returns bool/float/etc?

I'm trying to figure out why ConfigParser is giving Python types for the get() method, but items() is giving all strings, like 'True' instead of True, etc.

As a workaround I'm doing something like this:

log_settings = dict(CONF.items('log'))
for key, value in log_settings.items():
log_settings[key] = CONF.get('log', key)


Any thoughts on this?

Answer

From the ConfigParser source:

def items(self, section):
    try:
        d2 = self._sections[section]
    except KeyError:
        if section != DEFAULTSECT:
            raise NoSectionError(section)
        d2 = self._dict()
    d = self._defaults.copy()
    d.update(d2)
    if "__name__" in d:
        del d["__name__"]
    return d.items()

As you can see, .items() does no post-processing of the data to convert it to any type.


As a side note, are you sure .get isn't doing the same thing? The source code for .get does no coercing of the data, but .getboolean and co. do. Are you sure you aren't using .getboolean or .getfloat?

Below, you can see there is a helper ._get function that calls .get plus a conversion for the .getfloat etc.

def _get(self, section, conv, option):
    return conv(self.get(section, option))

def getfloat(self, section, option):
    return self._get(section, float, option)

The .get function has no such converion (it is done after .get in ._get)

def get(self, section, option):
    opt = self.optionxform(option)
    if section not in self._sections:
        if section != DEFAULTSECT:
            raise NoSectionError(section)
        if opt in self._defaults:
            return self._defaults[opt]
        else:
            raise NoOptionError(option, section)
    elif opt in self._sections[section]:
        return self._sections[section][opt]
    elif opt in self._defaults:
        return self._defaults[opt]
    else:
        raise NoOptionError(option, section)
Comments