By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,814 Members | 1,671 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,814 IT Pros & Developers. It's quick & easy.

Re: Singleton implementation problems

P: n/a
On Jul 3, 6:58 pm, Urizev <uri...@gmail.comwrote:
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?
Because __init__() is called to initialize the state of an object
*after* it has already been created. You should create a "new-style"
class and define __new__() instead. Here's a working version:

class Singleton(object): # new-style class
def __new__(cls, *args, **kwds):
# return the singleton (if already created)
try: return cls.__dict__['__singleton']
except KeyError: # raised only the first time for a given
class
# create the singleton and store it to the class namespace
singleton = object.__new__(cls, *args, **kwds)
setattr(cls, '__singleton', singleton)
return singleton

class X(Singleton):
def __init__(self, a): self.a = a

assert X(1) is X(2)
Note however that the classic Singleton pattern is usually frowned
upon in Python; the preferred approach is to use (module level)
globals. Also search for the "Borg pattern".

George
Jul 4 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.