Note that there are some explanatory texts on larger screens.

plurals
  1. POSingleton across modules
    primarykey
    data
    text
    <p>I'm trying to implement a Singleton and I am running into difficulty when I import the module. My set up is the following. I am using Python 2.7.</p> <h3>MODULE 1</h3> <pre><code>class SingletonClass(object): def __new__(self, *args, **kwargs): if not self._instance: self._instance = super(SingletonClass, self).__new__( self, *args, **kwargs) return self._instance print SingletonClass() #OUTPUT: 0x00000000030F1630 print SingletonClass() #OUTPUT: 0x00000000030F1630 (Good, what I want) </code></pre> <h3>MODULE 2</h3> <pre><code>import SingletonClass class AnotherClass: print SingletonClass.SingletonClass() #OUTPUT: 0x0000000003292208 </code></pre> <p>Within the module the singleton is working, but in another module the Singleton is not returning the same object as it did in the first. Any idea why?</p> <h3>Edit</h3> <p>For now I will put the only thing that I have found that works. I'm sure there is a better solution to this, but I think this may better convey what the underlying problem is.</p> <h3>MODULE 1</h3> <pre><code>class SingletonParent(object): _instance = None def __new__(self, *args, **kwargs): if not self._instance: self._instance = super(SingletonParent, self).__new__( self, *args, **kwargs) return self._instance </code></pre> <h3>MODULE 2</h3> <pre><code>import SingletonParent class SingletonClass(object): def __new__(self, *args, **kwargs): if not SingletonParent.SingletonParent._instance: SingletonParent.SingletonParent._instance = super(SingletonClass, self).__new__( self, *args, **kwargs) return SingletonParent.SingletonParent._instance print SingletonClass() #OUTPUT: 0x00000000030F1630 print SingletonClass() #OUTPUT: 0x00000000030F1630 </code></pre> <h3>MODULE 3</h3> <pre><code>import SingletonClass class AnotherClass: print SingletonClass.SingletonClass() #OUTPUT: 0x00000000030F1630 </code></pre> <h1>Solution (Edit 3)</h1> <p>Lesson: Don't have your main function in the same module as your Singleton!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload