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?
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 tosys.modulesunder the name__main__, and execution proceeds. When untitled imports test,sys.modulesis examined, no module namedtestis found, so test.py is executed again to import it. As a result, the class definition forAis executed twice, producing two distinct classes. The Singleton implementation therefore considers them distinct, and produces two instances.