Singleton implementation problems

Peter Otten __peter__ at web.de
Fri Jul 4 01:56:16 EDT 2008


Urizev wrote:

> Hi everyone
> 
> I have developed the singleton implementation. However I have found a
> strange behaviour when using from different files. The code is
> attached.
> 
> Executing main

> New singleton:
> <__main__.Singleton instance at 0x2b98be474a70>

> New singleton:
> <myset.Singleton instance at 0x2b98be474d88>

> I do not know why, but it creates two instances of the singleton. Does
> anybody know why?

Do you see it now I snipped the irrelevant output?

The problem is the structure of your program. The myset module is imported
twice by Python, once as "myset" and once as "__main__". Therefore you get
two distinct MySet classes, and consequently two distinct MySet.__instance
class attributes. 

Move the

if __name__ == "__main__": ...

statements into a separate module, e. g. main.py:

import myset
import member

if __name__ == "__main__":
    print "Executing main"
    set1 = myset.MySet()
    set2 = myset.MySet()

    mbr1 = member.Member()
    mbr2 = member.Member()
    mbr3 = member.Member()

Now main.py and member.py share the same instance of the myset module and
should work as expected.

Peter




More information about the Python-list mailing list