Help with Singleton SafeConfigParser

J

Josh English

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
 
P

Peter Otten

Josh said:
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.
 
J

Josh English

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 tryingthis sort of thing until then.

Thank you for the simple answer.

Josh
 
J

Josh English

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 tryingthis sort of thing until then.

Thank you for the simple answer.

Josh
 
M

Mark Lawrence

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

For the benefit of the OP and others, if you want to gain more knowledge
about patterns in Python such as the Singleton, I suggest you use your
favourite search engine to find "Alex Martelli Python patterns".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top