Mailing List Archive

Python and the Singleton Pattern
In article <y0jk8vuamz6.fsf@vier.idi.ntnu.no>, mlh@idt.ntnu.no (Magnus L. Hetland) wrote:
>
>But isn't the point that people should be able to use the singleton
>instantiator without knowing if it already has been instantiated, and
>always get the same instance?

Isn't it possible to make use of Python's dynamism to turn any
class into a singleton class, as needed?

For example:

class Singletonizer:
def __init__(self, base_class):
self.base_class = base_class
self.obj = None
def __call__(self, *args, **kw):
if self.obj is None:
self.obj = apply(self.base_class, args, kw)
return self.obj

# Now a test...

class Foo:
pass

Bar = Singletonizer(Foo)

x = Foo()
y = Foo()

a = Bar()
b = Bar()

if x is not y:
print "x and y are different objects"

if a is b:
print "a and b are the same object"

Which yields the right:

x and y are different objects
a and b are the same object

Then you can write your Foo class as usual, and then Singletonize
it as needed. If you are paranoid, you can name Foo "_Foo" so
that it won't be part of the module's exported interface.


Neel
Python and the Singleton Pattern [ In reply to ]
On Tue, 6 Apr 1999, Neelakantan Krishnaswami wrote:

> Isn't it possible to make use of Python's dynamism to turn any
> class into a singleton class, as needed?

<snipped implementation of class Singletonizer, which is basically a
class into a factory-function-which-always-returns the same object>

The problem with that, of course, is that it makes inheritance from
a singleton class impossible.

How about:

class MySingleton:
class _my_dummy: pass
_dummy=_my_dummy()
_initialized=0
def __init__(self, ....):
if initialized: return
......
def __getattr__(self, attr):
return _dummy.__dict__[attr]

def __setattr__(self, attr, val):
_dummy.__dict__[attr]=val

(I haven't tested it, but is seems like it should work)
--
Moshe Zadka <mzadka@geocities.com>.
QOTD: What fun to me! I'm not signing permanent.