Help with Singleton SafeConfigParser

Josh English Joshua.R.English at gmail.com
Sat Dec 8 18:48:04 CET 2012


On Saturday, December 8, 2012 9:40:07 AM UTC-8, Peter Otten wrote:
> 
> 
> 
> 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.


Ah. I was over-thinking again. I couldn't find an example of this anywhere, and when I saw the tirades against Singletons they mentioned "use modules" but, well, I haven't had my morning coffee yet. I shouldn't even be trying this sort of thing until then.

Thank you for the simple answer.

Josh



More information about the Python-list mailing list