Help with Singleton SafeConfigParser

Josh English Joshua.R.English at
Sat Dec 8 18:11:21 CET 2012

I am trying to create a Singleton SafeConfigParser object to use across all the various scripts in this application. 

I tried a Singleton pattern found on the web:

class Singleton(object):
    def __new__(cls):
        if not hasattr(cls, '_inst'):
            print "Creating Singleton Object"
            cls._inst = super(Singleton, cls).__new__(cls)
            print "Returning established Singleton"

        return cls._inst

import ConfigParser

class Options(ConfigParser.SafeConfigParser, Singleton):
    def __init__(self):
        print "Initialing Options"

And this doesn't work because it calls the __init__ method every time I create the Options object:


O = Options()
print O
print "from O", O.options('test')

P = Options()
print P
print "from P", P.options('test')

This results in:

Creating Singleton Object
Initialing Options
<__main__.Options object at 0x02BF4C50>
from O ['start']
Returning established Singleton
Initialing Options
<__main__.Options object at 0x02BF4C50>
from P []

I have seen older posts in this group that talk about using modules as singletons, but this, unless I misunderstand, requires me to code the entire API for SafeConfigParser in the module:

import ConfigParser

class Options(ConfigParser.SafeConfigParser):
    def __init__(self):
        self.readfp(open('defaults.cfg'))['local.txt', 'local.cfg'])

    def save(self):
        with open('local.txt','w') as f:

__options = Options()

def set(section, name, value):
    return self.__options.set(section, name, value)

def options(section):
    return self.__options.options

# And so on

This seems incredibly wasteful, and to introspect my options I get a module, not a SafeConfigParser object, so I'm wondering if there is a different way to handle this?


More information about the Python-list mailing list