Search code examples
pythonmodulesingletoninstances

Why do I get different instances of the same singleton in different modules?


I have 2 files that print a singleton instance, but I get two different instances.

I'm using Singleton code from Gary Robinson.

Here are the files:

test.py

from singleton import Singleton
import untitled

class A(Singleton):
    def __init__(self):
        super(A, self).__init__()        

if __name__ == "__main__":
    a = A.getInstance()
    print a
    untitled.print_a()

untitled.py

def print_a():
    import test
    print test.A.getInstance()

...and here is the output of python test.py

<__main__.A object at 0xaea270>
<test.A object at 0xaea3f0>

Can someone please explain to me what is happening (apparently at the module level) that is causing this behavior?


Solution

  • The reason you get two singletons is due to the way the modules are being imported. When you execute test.py from the command line, it is not known as test, it is __main__. An entry is added to sys.modules under the name __main__, and execution proceeds. When untitled imports test, sys.modules is examined, no module named test is found, so test.py is executed again to import it. As a result, the class definition for A is executed twice, producing two distinct classes. The Singleton implementation therefore considers them distinct, and produces two instances.