Dear Diary

A Developer’s Weblog

June, 2007

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: 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 [...]