Layered Python ConfigParser wrapper with support for environment vars

The full code (library + example + .ini files) for the following article are available at GitHub : https://github.com/davidohana/LayConf

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.

Image for post
Image for post

Example usage:

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

% example_LOG_file_backup_count=300 python example_app.py

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 : https://github.com/davidohana/LayConf

Happy Coding!

Written by

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store