1

my first question here:

I've searched the internet and also read several question and answers here before and finally figured out the way of writing the singleton classes for my python codes. I've also read the python documentation about the new() function and some other things but still confused about how and what is mean by all that new(cls, *args, **kw) things etc!

for example I wrote a test code like this:

class Singleton(object):

    def __new__(cls, *args, **kwargs):
        if '_inst' not in vars(cls):
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance

class printer(Singleton):

    def __init__(self):

        print "I am a new Object, and will remain until the end of time!"

if __name__ == '__main__':
    printer()

and the result is the text "I am a new Object, and will remain until the end of time!" But how this works, I mean, I don't know how to tell, for example I'm really confused about:

vars(cls): in the line if '_inst' not in vars(cls)

from where the vars(cls) comes out, I didn't declare that before! Can someone please clarify this things in the singleton class for me plus some about the last line

if __name__ == '__main__':
    printer()
  • Ironically, this attempt at a singleton isn't even working properly. Someone couldn't settle for one name, and now you can instanciate as many of them as you want... –  Mar 05 '11 at 17:12

3 Answers3

2

You should use modules as singletons in python, because they behave exactly like one.

Here is another question: Is there a simple, elegant way to define singletons?

Community
  • 1
  • 1
gruszczy
  • 40,948
  • 31
  • 128
  • 181
  • 1
    True, but no upvote since it doesn't really answer the question (explain teh codez). –  Mar 05 '11 at 17:15
2

First of all, this is wrong:

class Singleton(object):
    def __new__(cls, *args, **kwargs):
        if '_inst' not in vars(cls): # <-- this must of course also be "_instance"
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance

An explicit __new__ method can be used like the factory pattern, so when you write printer(), Python will first call __new__, passing the class type and the constructor parameters (in this example none).

'_instance' not in vars(cls) just means to look up whether the class already has an attribute called "_instance" (i.e. the singleton). If not, one is created. The trick with vars (builtin function, to answer your question) is not necessary, one could also use cls._instance and catch AttributeError, for example.

And the last thing:

if __name__ == '__main__':
    printer()

This just creates a printer instance (using Singleton.__new__) if the script is executed directly (i.e. if __name__ == '__main__', not if the module is imported).

AndiDog
  • 68,631
  • 21
  • 159
  • 205
  • Thanks AndiDog for your help. Can you explain a little bit more about the functions of __name__ and __main__ please? are these are the kinds of scopes or they are what? I've read that the __main__ is a scope where python keeps every piece of code that gets run from the interpreter or as standalone. – Mohammad Farjamfard Mar 06 '11 at 19:19
  • `__name__` is the name of the current module. That magic variable is usually used when writing launchers - if you execute a Python script directly, it will be imported by the Python interpreter as `__main__`. For example, some builtin modules behave differently when executed directly (e.g. SimpleHTTPServer runs a web server). Note that if the launched module is imported by its module name later, then you have two different modules, one is `__main__` and one is the named module. This [can lead to problems](http://stackoverflow.com/questions/5136159/basic-python-unittest-testsuite-question). – AndiDog Mar 06 '11 at 20:35
2

Instead of using a Singleton, have you considered using a Borg?

The idea is, because Python stores all the state for instances in an attribute (__dict__), if you simply reassign that attribute to a class attribute then you can instantiate the class as many times as they want but they will all have the same state.

Katriel
  • 120,462
  • 19
  • 136
  • 170