Globals and singletons in Python
<p>I have some few classes which are widespread in my Python application and which should have only one global instance (eg Logger, DbConnection). Python does not support static variables/methods in a class, so the usual Java/C++ way to create a singleton here does not work. I have looked for alternatives to implement singleton in Python. I want a simple (no metaprogramming if possible) and clean implementation. This looks good:</p>

<pre><code>class MyClass(object):
    def a():
        pass

singleton = MyClass()
</code></pre>

<p>Using the singleton would be simple as</p>

<pre><code>import myClass
myClass.singleton.a()
</code></pre>

<p>The direct assignment could be replaced by a creation function if object initialization is not so simple.</p>

<p>I could also create a getInstance() in module scope and always use it to get myObj.</p>

<p>Question 1) This works ok? The module code (myObj assignment) only runs the first time it is imported into some other module and myObj won't be created every time I import this module somewhere?</p>

<p>An alternative method I have seen is to use a globals module. Something like:</p>

<pre><code>from myClass1 import MyClass1
from myClass2 import MyClass2

myObj1 = MyClass1()
myObj2 = MyClass2()
</code></pre>

<p>Using this:</p>

<pre><code>import globals
globals.myObj1.a()
</code></pre>

<p>I tend to prefer the first alternative. </p>

<p>Question 2) Between the 2 solutions, what do you recommend? </p>

<p>Question 3) A third solution would be passing the widespread objects such as Logger to several classes/functions, but this is not a good solution imho. Is there a better solution not mentioned here  ?</p>

<p>I'm aware of the downsides of using global variables and singletons. However, having a global state is not a big issue in my application. I'll prefer solutions that have code clarity and are simple to use. </p>
