Working with Python ConfigParser

05 Apr 2014

Python ConfigParser module is useful when you want to set the defaults in a configuration file and have your application read the file, parse it and behave based on its contents. ConfigParser takes care of the reading and parsing part.

It accepts configuration files with structure similiar to INI files.

Some gotchas for using ConfigParser:

SafeConfigParser does not make any attempt to understand the option type. The application is expected to use the correct method to fetch the value as the desired type. get() always returns a string. Use getint() for integers, getfloat() for floating point numbers, and getboolean() for boolean values.

Also, mind the ConfigParser API differences (especially constructors) between python 2.6 and python 2.7.

For your own interests, the value searching algorithm for those parsers (SafeConfigParser, RawConfigParser, ConfigParser) is like this:

  1. Before starting the option search, the section name is tested. If the section does not exist, and the name is not the special value DEFAULT, then NoSectionError is raised.
  2. If the option name appears in the vars dictionary passed to get(), the value from vars is returned.
  3. If the option name appears in the specified section, the value from that section is returned.
  4. If the option name appears in the DEFAULT section, that value is returned.
  5. If the option name appears in the defaults dictionary passed to the constructor, that value is returned.
  6. If the name is not found in any of those locations, NoOptionError is raised.

For more details, please check out PyMOTW: