ActiveState Code

Recipe 519627: Singleton Base Class


Here I have implemented the Singleton base class using __new__. I was reading thru Bruce Eckel's http://www.mindview.net/Books/TIPython and thought OnlyOne can be more simple....

Are there any differences in between two approaches?

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class OnlyOne(object):
    """
    Signleton class , only one obejct of this type can be created
    any class derived from it will be Singleton
    """
    __instance = None
    def __new__(typ, *args, **kwargs):
        if OnlyOne.__instance == None:
            obj = object.__new__(typ, *args, **kwargs)
            OnlyOne.__instance = obj
            
        return OnlyOne.__instance

print OnlyOne() == OnlyOne()

# testing derived class

class My1(OnlyOne): pass 

print My1() == My1()

Comments

  1. 1. At 8:08 a.m. on 10 may 2007, Steven Bethard said:
  2. 2. At 1:57 p.m. on 10 may 2007, thanos vassilakis said:

    Is this just noise? The solution is okay, but I've seen hundreds of these, and some exactly the same. This entry looks like noise in an attempt to ... ... maybe create presence ? Is the submitter planning a patent application. He won't be the first.

  3. 3. At 10:31 a.m. on 15 may 2007, David Fung said:
        if OnlyOne.__instance == None:
    
            obj = object.__new__(typ, *args, **kwargs)
    
            OnlyOne.__instance = obj
    

    looks like we need to make this three lines atomic...

  4. 4. At 5:44 a.m. on 18 oct 2007, anurag uniyal (the author) said:

    My porpose in neither to generate noise nor presence... i just wanted to know how is the solution and which one i use if i need signleton?

Sign in to comment