Help with Singleton SafeConfigParser

Peter Otten __peter__ at web.de
Sat Dec 8 18:40:07 CET 2012


Josh English wrote:

> 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?

Two underscores trigger name mangling only in a class, not in a module. 
Don't try to hide the Options instance:

# module config.py
import ConfigParser

class Options(ConfigParser.SafeConfigParser):
     ... # as above

options = Options()

Then use it elsewhere:

from config import options

options.set("mysection", "myoption", "myvalue")

All but the first import will find the module in the cache (sys.modules) and 
therefore the same Options instance will be used. Voilà your no-nonsense 
singleton.




More information about the Python-list mailing list