#define equivalents and config files

Andy Gimblett gimbo at ftech.net
Thu Mar 21 05:24:04 EST 2002


On Thu, Mar 21, 2002 at 08:53:07AM +0000, Dave Swegen wrote:

> I'm basically after a single file where such values can be stored, and
> then used in various parts of the program without having to pass extra
> configuation variables around.

Well, this might be overkill depending on the size of your system, but
I quite often use the singleton design pattern for this purpose: I
have a module called Config which has a Config() function for
accessing the singleton.  Working demo:

-- begin Config.py

#!/usr/bin/env python

_configInstance = None

def Config():
    # This function, and _only_ this function, should be used to
    # access _configInstance.
    global _configInstance
    if _configInstance is None:
        _configInstance = _config()
    return _configInstance

class _config:

    def __init__(self):
        # Initialise from wherever, eg hard-coded, read from file on
        # disk (maybe using ConfigParser), checking command-line
        # parameters using getopt, etc.
        self.foobar = 'spam!'

-- end Config.py

-- begin client.py

#!/usr/bin/env python

import Config

def foo():
    config = Config.Config()
    print config.foobar

foo()

-- end client.py

As I say, this may be overkill depending on the size of your system,
but for largish systems it can be quite handy because it saves you
from, as you put it, "having to pass extra configuation variables
around".  I typically use it when I've got more than, say, three
modules which need to share config information.

-Andy

-- 
Andy Gimblett - Programmer - Frontier Internet Services Limited
Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/
Statements made are at all times subject to Frontier's Terms and
Conditions of Business, which are available upon request.




More information about the Python-list mailing list