Layered Python ConfigParser wrapper with support for environment vars

The full code (library + example + .ini files) for the following article are available at GitHub :

In every programming language I use, one of the first thing I need is a decent configuration library.

My requirements are usually:

  • Default (hard-coded) configuration
  • Custom configuration file
  • Ability to override configuration entries from environment variables and command-line arguments

In Python, the existing packages I found seems to be an overkill, or it might just be my NIH syndrome. But anyway, after some search, I shamelessly copied and modified this.

The result is a small and simple class that supports most of what I need.

Configuration options are first looked up at env var {section}_{option}, then in a custom .ini file, then in the default .ini file. It's also possible to add inline defaults if the entry does not exist in the default .ini file.

Example usage:

First Layer of configuration is cfg/default.ini with all default values
The second Layer of configuration is cfg/staging.ini, override just what you want to change:
Application code

Now, let's run it while overriding one config option:

% example_LOG_file_backup_count=300 python

and the output would be:

config env prefix: example
config default: cfg/default.ini
config custom: cfg/staging.ini
env_name: staging
console_enabled: True
file_rotation_size_mb: 10
'foo' not found
foo: bar
foo_number: 33
file_enabled: true
file_backup_count: 300

The full code (library + example + .ini files) are available at GitHub :

Happy Coding!

Software developer & research staff member @ IBM (Haifa Research Lab)