Initializing defaults to module variables

Fredrik Lundh fredrik at pythonware.com
Thu Apr 13 12:21:06 EDT 2006


Burton Samograd wrote:

> A reply to my own question, but I thought I would share the answer.  I
> got it to work with the following code:
>
> import config
> import sys
> from posix import environ
> sys.path.insert(0, environ["HOME"]+"/.program")
> reload(config)
>
> I have a file in my working directory that contains all the program
> variables with default values called config.py, which is loaded at the
> start, and then the user configuration directory is inserted into the
> load path and then their config.py is loaded, which will then
> overwrite the default values.

since you know the name of the config file you're looking for, you can
simplify (and unweirdify) your code a bit by changing your config file to
look like this:

    # File: config.py

    #
    # configuration defaults

    some_param = "value"
    some_other_param = 1

    #
    # get user overrides

    import os
    try:
        execfile(os.path.expanduser("~/.program/config.py"))
    except IOError:
        pass # ignore missing config file, but not syntax errors

    # end of file

with this in place, you just have to do

    import config

in any application module than needs to access the configuration data.

</F>






More information about the Python-list mailing list