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: <pre> class Singleton(object): def __new__(cls): if not hasattr(cls, '_inst'): print "Creating Singleton Object" cls._inst = super(Singleton, cls).__new__(cls) else: print "Returning established Singleton" return cls._inst import ConfigParser class Options(ConfigParser.SafeConfigParser, Singleton): def __init__(self): print "Initialing Options" ConfigParser.SafeConfigParser.__init__(self) self.add_section('test') </pre> And this doesn't work because it calls the __init__ method every time I create the Options object: <pre> O = Options() print O O.set('test','start','True') print "from O", O.options('test') P = Options() print P print "from P", P.options('test') </pre> This results in: <pre> 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 [] </pre> 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: <pre> import ConfigParser class Options(ConfigParser.SafeConfigParser): def __init__(self): ConfigParser.SafeConfigParser.__init__(self) self.readfp(open('defaults.cfg')) self.read(['local.txt', 'local.cfg']) def save(self): with open('local.txt','w') as f: self.write(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 </pre> 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? Josh -- http://mail.python.org/mailman/listinfo/python-list