The Python way of handling configuration settings

Qt 3.0 offers a nice and integrated way of handling configuration settings. The Qt 3.0 way of working wasn't quite ready when I was writing this chapter, so I've just added a forward-looking statement in the last section of this chapter on how things will work Qt 3.0 is bound to Python.

Creating a configuration management framework is an interesting exercise in its own right, so, after exploring the standard modules Python offers, we'll build a simple framework that neatly fits kalam ourselves.

For now, the choice is between taking the easy way out, or conducting a really nice cross-platform solution. The easy way out is to store all settings in a settings file, both on Unix and on Windows. We can store this file in $HOME/.kalamrc, and prompt the Windows users to enter a setting for HOME in their control panel.

To store user settings the "right" way, the editor will have to determine if it is running on a Windows or Unix system. On Windows, the editor will store all configuration files in the registry (using the Python module _winreg), and on Linux in a dot file in the users home directory. We can structure the dot file with the Python ConfigParser module, which can read and write files of the old Windows .ini format.

As the name implies, _winreg is a very low-level library, and only suitable to build something on top that is more complete. Furthermore, the way in which ConfigParser deals with settings, while very elegant, is not really compatible with _winreg. We will first take a look at the easy way out: after all, within the foreseeable future we'll have Qt 3.0's QConfig, which will obsolete our own efforts.

If you want to keep your application firmly in the Python domain—perhaps with a view to later translate the application to another GUI toolkit—you can use ConfigParser and _winreg (for Windows and Unix, respectively). You can determine which platform your application runs on with the following check:

if sys.platform=="win32":
    import _winreg
    # handle reading and writing of configuration data using
    # the registry
else:
    import ConfigParser
    # handle reading and writing of configuration data using
    # the configuration files that are structured like windows
    # .ini files.
    

Discussing these standard Python library modules is a bit beyond the scope of this book. You can find descriptions of them in the Python Library Reference. Regardless of the solution you choose, you should be able to use the same central configuration object — an object which we are now going to develop.