Singleton implementation problems

Matthew Fitzgibbons elessar at nienna.org
Thu Jul 3 19:11:34 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 MySet object
> No singleton instance
> New singleton:
> <__main__.Singleton instance at 0x2b98be474a70>
> new MySet object
> There is a singlenton instance
> new Member
> new MySet object
> No singleton instance
> New singleton:
> <myset.Singleton instance at 0x2b98be474d88>
> new Member
> new MySet object
> There is a singlenton instance
> new Member
> new MySet object
> There is a singlenton instance
> 
> I do not know why, but it creates two instances of the singleton. Does
> anybody know why?
> 
> Regards
> 
> 
> ------------------------------------------------------------------------
> 
> --
> http://mail.python.org/mailman/listinfo/python-list

I've run into a similar problem. Basically, when you refer to a class 
from __main__ (i.e., the .py file you're actually running) versus from 
an imported module, Python doesn't realize they're the same class. Your 
Singleton implementation is creating one instance for __main__ and one 
for everything else. I'm sure there's someone around here who can say 
why Python behaves this way. You should be fine if you can restructure 
your code so you don't use your Singleton from __main__. In my case, I 
added a new main.py file.

-Matt



More information about the Python-list mailing list