Singleton Pattern in Python

I was looking for a smooth way to create singletons in python. Here is a metaclass solution that seems to work:

Python
1
2
3
4
5
6
7
8
class Singleton(type):
def __init__(cls,name,bases,dic):
super(Singleton,cls).__init__(name,bases,dic)
cls.instance=None
def __call__(cls,*args,**kw):
if cls.instance is None:
cls.instance=super(Singleton,cls).__call__(*args,**kw)
return cls.instance

This was originally posted by Michele Simionato as a comment on a python singleton recipe on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/102187

You use it like this:

Python
1
2
3
class A( object ):
__metaclass__ = Singleton
# here goes the rest of you class definiton ..

But you knew that anyway, didn’t you? ;)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">