Is this python pattern for a singleton safe?
<p>I have a module R that handles gets and sets to a redis cluster. It is imported all over a flask api's endpoints. My first thought was to use a Singleton class in R so that we maintain one single connection to the redis cluster, but I'm not entirely I should putting a singleton class pattern into a code base that is only looked at once a year by different developers, I really don't want someone trying to instantiate it multiple times at a later stage. </p>

<p>So, instead, in my module <strong>init</strong>.py I set up the connection to the cluster, and import this connection to my redis cluster module, then whereever I use R, the connection is always the same connection without having to use a singleton. </p>

<p>e.g.:</p>

<p><strong>_init</strong> _.py:</p>

<pre><code> try:
 RedisConnection = ConnectionMaker(...)
</code></pre>

<p><strong>R</strong>.py:</p>

<pre><code>from ...caching import RedisConnection
...
def set_cache():
    RedisConnection.set(....)
</code></pre>

<p>some_endpoint.py</p>

<pre><code> from ....caching import set_cache, ...
</code></pre>

<p>some_other_endpoint.py</p>

<pre><code> from ....caching import set_cache, ...
</code></pre>

<p>I think this is safe because '<a href="http://stackoverflow.com/questions/10936709/why-does-a-python-module-act-like-a-singleton">Since Python modules are first-class runtime objects, they effectively become singletons, initialized at the time of first import.</a>'. However, is there anything that I am missing, anything dangerous?</p>

<p>It is safe but there are two things I don't think are good practices.</p>

<ol>
<li>Initializations or class definitions etc should not be there in
init.py Init file is use to hide internal structure of the package.
A simple <strong>init</strong>.py is a good <strong>init</strong>.py </li>
<li>Creating objects in global space is not good. Disadvantage of is that mere importing your package will consume memory since it initializes an object. You should make actual connection inside a class or a function. Whenever you need a connection call this class or function to create a singleton connection.</li>
</ol>

python singleton python-module