<p>There seem to be many ways to define <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">singletons</a> in Python. Is there a consensus opinion on Stack&nbsp;Overflow?</p>

[{'answer_id': 31884, 'author': 'John', 'author_id': 2168, 'author_profile': 'https://Stackoverflow.com/users/2168', 'pm_score': 2, 'selected': False, 'text': '<p>Being relatively new to Python I\'m not sure what the most common idiom is, but the simplest thing I can think of is just using a module instead of a class. What would have been instance methods on your class become just functions in the module and any data just becomes variables in the module instead of members of the class. I suspect this is the pythonic approach to solving the type of problem that people use singletons for.</p>\n\n<p>If you really want a singleton class, there\'s a reasonable implementation described on the <a href="http://www.python.org/workshops/1997-10/proceedings/savikko.html" rel="nofollow noreferrer">first hit on Google</a> for "Python singleton", specifically:</p>\n\n<pre><code>class Singleton:\n    __single = None\n    def __init__( self ):\n        if Singleton.__single:\n            raise Singleton.__single\n        Singleton.__single = self\n</code></pre>\n\n<p>That seems to do the trick.</p>\n'}, {'answer_id': 31887, 'author': 'Staale', 'author_id': 3355, 'author_profile': 'https://Stackoverflow.com/users/3355', 'pm_score': 10, 'selected': True, 'text': "<p>I don't really see the need, as a module with functions (and not a class) would serve well as a singleton. All its variables would be bound to the module, which could not be instantiated repeatedly anyway. </p>\n\n<p>If you do wish to use a class, there is no way of creating private classes or private constructors in Python, so you can't protect against multiple instantiations, other than just via convention in use of your API. I would still just put methods in a module, and consider the module as the singleton.</p>\n"}, {'answer_id': 32487, 'author': 'Peter Hoffmann', 'author_id': 720, 'author_profile': 'https://Stackoverflow.com/users/720', 'pm_score': 7, 'selected': False, 'text': '<p>A slightly different approach to implement the singleton in Python is the <a href="http://code.activestate.com/recipes/66531/" rel="noreferrer">borg pattern</a> by Alex Martelli (Google employee and Python genius).</p>\n\n<pre><code>class Borg:\n    __shared_state = {}\n    def __init__(self):\n        self.__dict__ = self.__shared_state\n</code></pre>\n\n<p>So instead of forcing all instances to have the same identity, they share state.</p>\n'}, {'answer_id': 33201, 'author': 'Acuminate', 'author_id': 2482, 'author_profile': 'https://Stackoverflow.com/users/2482', 'pm_score': 6, 'selected': False, 'text': '<p>The module approach works well. If I absolutely need a singleton I prefer the Metaclass approach.</p>\n\n<pre><code>class Singleton(type):\n    def __init__(cls, name, bases, dict):\n        super(Singleton, cls).__init__(name, bases, dict)\n        cls.instance = None \n\n    def __call__(cls,*args,**kw):\n        if cls.instance is None:\n            cls.instance = super(Singleton, cls).__call__(*args, **kw)\n        return cls.instance\n\nclass MyClass(object):\n    __metaclass__ = Singleton\n</code></pre>\n'}, {'answer_id': 35080, 'author': 'David Locke', 'author_id': 1447, 'author_profile': 'https://Stackoverflow.com/users/1447', 'pm_score': 4, 'selected': False, 'text': '<p>The one time I wrote a singleton in Python I used a class where all the member functions had the classmethod decorator.</p>\n<pre><code>class Foo:\n    x = 1\n  \n    @classmethod\n    def increment(cls, y=1):\n        cls.x += y\n</code></pre>\n'}, {'answer_id': 42562, 'author': 'Mark Biek', 'author_id': 305, 'author_profile': 'https://Stackoverflow.com/users/305', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://code.activestate.com/recipes/52558/" rel="nofollow noreferrer">The Singleton Pattern implemented with Python</a> courtesy of ActiveState.</p>\n\n<p>It looks like the trick is to put the class that\'s supposed to only have one instance inside of another class.</p>\n'}, {'answer_id': 61984, 'author': 'FrankS', 'author_id': 3134, 'author_profile': 'https://Stackoverflow.com/users/3134', 'pm_score': 3, 'selected': False, 'text': '<p>There are also some interesting articles on the Google Testing blog, discussing why singleton are/may be bad and are an anti-pattern:</p>\n\n<ul>\n<li><a href="http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-join-new-project.html" rel="noreferrer">Singletons are Pathological Liars</a></li>\n<li><a href="http://googletesting.blogspot.com/2008/08/where-have-all-singletons-gone.html" rel="noreferrer">Where Have All the Singletons Gone?</a></li>\n<li><a href="http://googletesting.blogspot.com/2008/08/root-cause-of-singletons.html" rel="noreferrer">Root Cause of Singletons</a></li>\n</ul>\n'}, {'answer_id': 1314783, 'author': 'u0b34a0f6ae', 'author_id': 137317, 'author_profile': 'https://Stackoverflow.com/users/137317', 'pm_score': 5, 'selected': False, 'text': "<p>I'm very unsure about this, but my project uses 'convention singletons' (not enforced singletons), that is, if I have a class called <code>DataController</code>, I define this in the same module:</p>\n\n<pre><code>_data_controller = None\ndef GetDataController():\n    global _data_controller\n    if _data_controller is None:\n        _data_controller = DataController()\n    return _data_controller\n</code></pre>\n\n<p>It is not elegant, since it's a full six lines. But all my singletons use this pattern, and it's at least very explicit (which is pythonic).</p>\n"}, {'answer_id': 1810367, 'author': 'jojo', 'author_id': 287210, 'author_profile': 'https://Stackoverflow.com/users/287210', 'pm_score': 8, 'selected': False, 'text': '<p>You can override the <code>__new__</code> method like this: </p>\n\n<pre><code>class Singleton(object):\n    _instance = None\n    def __new__(cls, *args, **kwargs):\n        if not cls._instance:\n            cls._instance = super(Singleton, cls).__new__(\n                                cls, *args, **kwargs)\n        return cls._instance\n\n\nif __name__ == \'__main__\':\n    s1 = Singleton()\n    s2 = Singleton()\n    if (id(s1) == id(s2)):\n        print "Same"\n    else:\n        print "Different"\n</code></pre>\n'}, {'answer_id': 1922376, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<pre><code>class Singleton(object[,...]):\n\n    staticVar1 = None\n    staticVar2 = None\n\n    def __init__(self):\n        if self.__class__.staticVar1==None :\n            # create class instance variable for instantiation of class\n            # assign class instance variable values to class static variables\n        else:\n            # assign class static variable values to class instance variables\n</code></pre>\n'}, {'answer_id': 2752280, 'author': 'Wei', 'author_id': 330650, 'author_profile': 'https://Stackoverflow.com/users/330650', 'pm_score': 6, 'selected': False, 'text': '<p>See this implementation from <a href="http://www.python.org/dev/peps/pep-0318/#examples" rel="noreferrer">PEP318</a>, implementing the singleton pattern with a decorator:</p>\n\n<pre><code>def singleton(cls):\n    instances = {}\n    def getinstance():\n        if cls not in instances:\n            instances[cls] = cls()\n        return instances[cls]\n    return getinstance\n\n@singleton\nclass MyClass:\n    ...\n</code></pre>\n'}, {'answer_id': 6843917, 'author': 'Mark Evans', 'author_id': 228670, 'author_profile': 'https://Stackoverflow.com/users/228670', 'pm_score': 3, 'selected': False, 'text': '<p>I think that <strong>forcing</strong> a class or an instance to be a singleton is overkill. Personally, I like to define a normal instantiable class, a semi-private reference, and a simple factory function.</p>\n\n<pre><code>class NothingSpecial:\n    pass\n\n_the_one_and_only = None\n\ndef TheOneAndOnly():\n    global _the_one_and_only\n    if not _the_one_and_only:\n        _the_one_and_only = NothingSpecial()\n    return _the_one_and_only\n</code></pre>\n\n<p>Or if there is no issue with instantiating when the module is first imported:</p>\n\n<pre><code>class NothingSpecial:\n    pass\n\nTHE_ONE_AND_ONLY = NothingSpecial()\n</code></pre>\n\n<p>That way you can write tests against fresh instances without side effects, and there is no need for sprinkling the module with global statements, and if needed you can derive variants in the future.</p>\n'}, {'answer_id': 7346105, 'author': 'Paul Manta', 'author_id': 627005, 'author_profile': 'https://Stackoverflow.com/users/627005', 'pm_score': 9, 'selected': False, 'text': '<p>Here\'s my own implementation of singletons. All you have to do is decorate the class; to get the singleton, you then have to use the <code>Instance</code> method. Here\'s an example:</p>\n\n\n\n<pre><code>@Singleton\nclass Foo:\n   def __init__(self):\n       print \'Foo created\'\n\nf = Foo() # Error, this isn\'t how you get the instance of a singleton\n\nf = Foo.instance() # Good. Being explicit is in line with the Python Zen\ng = Foo.instance() # Returns already created instance\n\nprint f is g # True\n</code></pre>\n\n<p>And here\'s the code:</p>\n\n<pre><code>class Singleton:\n    """\n    A non-thread-safe helper class to ease implementing singletons.\n    This should be used as a decorator -- not a metaclass -- to the\n    class that should be a singleton.\n\n    The decorated class can define one `__init__` function that\n    takes only the `self` argument. Also, the decorated class cannot be\n    inherited from. Other than that, there are no restrictions that apply\n    to the decorated class.\n\n    To get the singleton instance, use the `instance` method. Trying\n    to use `__call__` will result in a `TypeError` being raised.\n\n    """\n\n    def __init__(self, decorated):\n        self._decorated = decorated\n\n    def instance(self):\n        """\n        Returns the singleton instance. Upon its first call, it creates a\n        new instance of the decorated class and calls its `__init__` method.\n        On all subsequent calls, the already created instance is returned.\n\n        """\n        try:\n            return self._instance\n        except AttributeError:\n            self._instance = self._decorated()\n            return self._instance\n\n    def __call__(self):\n        raise TypeError(\'Singletons must be accessed through `instance()`.\')\n\n    def __instancecheck__(self, inst):\n        return isinstance(inst, self._decorated)\n</code></pre>\n'}, {'answer_id': 7927702, 'author': 'mkm', 'author_id': 246621, 'author_profile': 'https://Stackoverflow.com/users/246621', 'pm_score': 0, 'selected': False, 'text': '<p>In cases where you don\'t want the metaclass-based solution above, and you don\'t like the simple function decorator-based approach (e.g. because in that case static methods on the singleton class won\'t work), this compromise works:</p>\n\n<pre><code>class singleton(object):\n  """Singleton decorator."""\n\n  def __init__(self, cls):\n      self.__dict__[\'cls\'] = cls\n\n  instances = {}\n\n  def __call__(self):\n      if self.cls not in self.instances:\n          self.instances[self.cls] = self.cls()\n      return self.instances[self.cls]\n\n  def __getattr__(self, attr):\n      return getattr(self.__dict__[\'cls\'], attr)\n\n  def __setattr__(self, attr, value):\n      return setattr(self.__dict__[\'cls\'], attr, value)\n</code></pre>\n'}, {'answer_id': 8296319, 'author': 'Tiezhen', 'author_id': 1052083, 'author_profile': 'https://Stackoverflow.com/users/1052083', 'pm_score': 2, 'selected': False, 'text': '<p>My simple solution which is based on the default value of function parameters.</p>\n\n<pre><code>def getSystemContext(contextObjList=[]):\n    if len( contextObjList ) == 0:\n        contextObjList.append( Context() )\n        pass\n    return contextObjList[0]\n\nclass Context(object):\n    # Anything you want here\n</code></pre>\n'}, {'answer_id': 9403992, 'author': 'Matt Alcock', 'author_id': 200983, 'author_profile': 'https://Stackoverflow.com/users/200983', 'pm_score': 4, 'selected': False, 'text': '<p>Creating a singleton decorator (aka an annotation) is an elegant way if you want to decorate (annotate) classes going forward. Then you just put @singleton before your class definition. </p>\n\n<pre><code>def singleton(cls):\n    instances = {}\n    def getinstance():\n        if cls not in instances:\n            instances[cls] = cls()\n        return instances[cls]\n    return getinstance\n\n@singleton\nclass MyClass:\n    ...\n</code></pre>\n'}, {'answer_id': 9489387, 'author': 'Mychot sad', 'author_id': 1126139, 'author_profile': 'https://Stackoverflow.com/users/1126139', 'pm_score': 2, 'selected': False, 'text': "<p>OK, singleton could be good or evil, I know. This is my implementation, and I simply extend a classic approach to introduce a cache inside and produce many instances of a different type or, many instances of same type, but with different arguments.</p>\n\n<p>I called it Singleton_group, because it groups similar instances together and prevent that an object of the same class, with same arguments, could be created:</p>\n\n<pre><code># Peppelinux's cached singleton\nclass Singleton_group(object):\n    __instances_args_dict = {}\n    def __new__(cls, *args, **kwargs):\n        if not cls.__instances_args_dict.get((cls.__name__, args, str(kwargs))):\n            cls.__instances_args_dict[(cls.__name__, args, str(kwargs))] = super(Singleton_group, cls).__new__(cls, *args, **kwargs)\n        return cls.__instances_args_dict.get((cls.__name__, args, str(kwargs)))\n\n\n# It's a dummy real world use example:\nclass test(Singleton_group):\n    def __init__(self, salute):\n        self.salute = salute\n\na = test('bye')\nb = test('hi')\nc = test('bye')\nd = test('hi')\ne = test('goodbye')\nf = test('goodbye')\n\nid(a)\n3070148780L\n\nid(b)\n3070148908L\n\nid(c)\n3070148780L\n\nb == d\nTrue\n\n\nb._Singleton_group__instances_args_dict\n\n{('test', ('bye',), '{}'): &lt;__main__.test object at 0xb6fec0ac&gt;,\n ('test', ('goodbye',), '{}'): &lt;__main__.test object at 0xb6fec32c&gt;,\n ('test', ('hi',), '{}'): &lt;__main__.test object at 0xb6fec12c&gt;}\n</code></pre>\n\n<p>Every object carries the singleton cache... This could be evil, but it works great for some :)</p>\n"}, {'answer_id': 11517201, 'author': 'Brian Bruggeman', 'author_id': 631199, 'author_profile': 'https://Stackoverflow.com/users/631199', 'pm_score': 5, 'selected': False, 'text': '<p>The <a href="http://www.python.org/download/releases/2.2/descrintro/#__new__" rel="noreferrer">Python documentation</a> does cover this:</p>\n<pre><code>class Singleton(object):\n    def __new__(cls, *args, **kwds):\n        it = cls.__dict__.get(&quot;__it__&quot;)\n        if it is not None:\n            return it\n        cls.__it__ = it = object.__new__(cls)\n        it.init(*args, **kwds)\n        return it\n    def init(self, *args, **kwds):\n        pass\n</code></pre>\n<p>I would probably rewrite it to look more like this:</p>\n<pre><code>class Singleton(object):\n    &quot;&quot;&quot;Use to create a singleton&quot;&quot;&quot;\n    def __new__(cls, *args, **kwds):\n        &quot;&quot;&quot;\n        &gt;&gt;&gt; s = Singleton()\n        &gt;&gt;&gt; p = Singleton()\n        &gt;&gt;&gt; id(s) == id(p)\n        True\n        &quot;&quot;&quot;\n        it_id = &quot;__it__&quot;\n        # getattr will dip into base classes, so __dict__ must be used\n        it = cls.__dict__.get(it_id, None)\n        if it is not None:\n            return it\n        it = object.__new__(cls)\n        setattr(cls, it_id, it)\n        it.init(*args, **kwds)\n        return it\n\n    def init(self, *args, **kwds):\n        pass\n\n\nclass A(Singleton):\n    pass\n\n\nclass B(Singleton):\n    pass\n\n\nclass C(A):\n    pass\n\n\nassert A() is A()\nassert B() is B()\nassert C() is C()\nassert A() is not B()\nassert C() is not B()\nassert C() is not A()\n</code></pre>\n<p>It should be relatively clean to extend this:</p>\n<pre><code>class Bus(Singleton):\n    def init(self, label=None, *args, **kwds):\n        self.label = label\n        self.channels = [Channel(&quot;system&quot;), Channel(&quot;app&quot;)]\n        ...\n</code></pre>\n'}, {'answer_id': 11965327, 'author': 'Volodymyr Pavlenko', 'author_id': 655500, 'author_profile': 'https://Stackoverflow.com/users/655500', 'pm_score': 2, 'selected': False, 'text': '<pre><code>class Singeltone(type):\n    instances = dict()\n\n    def __call__(cls, *args, **kwargs):\n        if cls.__name__ not in Singeltone.instances:            \n            Singeltone.instances[cls.__name__] = type.__call__(cls, *args, **kwargs)\n        return Singeltone.instances[cls.__name__]\n\n\nclass Test(object):\n    __metaclass__ = Singeltone\n\n\ninst0 = Test()\ninst1 = Test()\nprint(id(inst1) == id(inst0))\n</code></pre>\n'}, {'answer_id': 12850496, 'author': 'Lambda Fairy', 'author_id': 617159, 'author_profile': 'https://Stackoverflow.com/users/617159', 'pm_score': 5, 'selected': False, 'text': '<p>As the <a href="https://stackoverflow.com/a/31887/617159">accepted answer</a> says, the most idiomatic way is to just <strong>use a module</strong>.</p>\n\n<p>With that in mind, here\'s a proof of concept:</p>\n\n<pre><code>def singleton(cls):\n    obj = cls()\n    # Always return the same object\n    cls.__new__ = staticmethod(lambda cls: obj)\n    # Disable __init__\n    try:\n        del cls.__init__\n    except AttributeError:\n        pass\n    return cls\n</code></pre>\n\n<p>See the <a href="http://docs.python.org/3/reference/datamodel.html#object.__new__" rel="noreferrer">Python data model</a> for more details on <code>__new__</code>.</p>\n\n<p>Example:</p>\n\n<pre><code>@singleton\nclass Duck(object):\n    pass\n\nif Duck() is Duck():\n    print "It works!"\nelse:\n    print "It doesn\'t work!"\n</code></pre>\n\n<p>Notes:</p>\n\n<ol>\n<li><p>You have to use new-style classes (derive from <code>object</code>) for this.</p></li>\n<li><p>The singleton is initialized when it is defined, rather than the first time it\'s used.</p></li>\n<li><p>This is just a toy example. I\'ve never actually used this in production code, and don\'t plan to.</p></li>\n</ol>\n'}, {'answer_id': 14280940, 'author': 'neu-rah', 'author_id': 1329075, 'author_profile': 'https://Stackoverflow.com/users/1329075', 'pm_score': 2, 'selected': False, 'text': "<p><strong>Singleton's half brother</strong></p>\n\n<p>I completely agree with staale and I leave here a sample of creating a singleton half brother:</p>\n\n<pre><code>class void:pass\na = void();\na.__class__ = Singleton\n</code></pre>\n\n<p><code>a</code> will report now as being of the same class as singleton even if it does not look like it. So singletons using complicated classes end up depending on we don't mess much with them.</p>\n\n<p>Being so, we can have the same effect and use simpler things like a variable or a module. Still, if we want use classes for clarity and because <strong>in Python a class is an object</strong>, so we already have the object (not and instance, but it will do just like).</p>\n\n<pre><code>class Singleton:\n    def __new__(cls): raise AssertionError # Singletons can't have instances\n</code></pre>\n\n<p>There we have a nice assertion error if we try to create an instance, and we can store on derivations static members and make changes to them at runtime (I love Python). This object is as good as other about half brothers (you still can create them if you wish), however it will tend to run faster due to simplicity.</p>\n"}]
['https://Stackoverflow.com/questions/31875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3363/']