an example of a singleton design pattern in python?

Jeff Epler jepler at unpythonic.net
Wed Jan 21 20:25:16 EST 2004


On Wed, Jan 21, 2004 at 07:38:26PM -0500, Aahz wrote:
> * Within a single module, use a global class as your singleton object.

This is a little bit inconvenient, because you must either mark all
methods as staticmethod (and refer to the class by name), or you must
mark all methods as classmethod.

This metaclass can help.  It makes all functions into staticmethods at
the time the class is created:

    from types import FunctionType

    class SingletonClassMeta(type):
	def __new__(cls, name, bases, dict):
	    for k, v in dict.iteritems():
		if isinstance(v, FunctionType):
		    dict[k] = classmethod(v)
	    return (super(SingletonClassMeta, cls).
			__new__(cls, name, bases, dict))

    class Singleton(object):
	"""All methods in a Singleton object are made class methods"""
	__metaclass__ = SingletonClassMeta

Probably __init__ should be made to raise an exception (RuntimeError,
"Singletons cannot be instantiated"))...

An example:
>>> class C(Singleton):
...     x = []
...     def f(self): return self.x
...     def g(self, arg): self.x.append(arg)
... 
>>> C.f()
[]
>>> C.g(3)
>>> C.f()
[3]




More information about the Python-list mailing list