Singleton class: what is the purpose?
Just
just at xs4all.nl
Thu Jun 5 08:30:08 EDT 2003
In article <mailman.1054811769.993.python-list at python.org>,
Gerrit Holl <gerrit at nl.linux.org> wrote:
> Guido's article on unifying types and classes mentions singleton classes.
> It says:
>
> """
> As another example of __new__, here's a
> way to implement the singleton pattern.
> """
> (http://www.python.org/2.2.3/descrintro.html)
>
> What is a singleton class? What is the purpose of a singleton class?
>
> On the web, I have found that a singleton class allows only one instance.
> Is that correct?
Yes.
> If so, it should be easily implementable with:
>
> 20 >>> class Singleton(object):
> 20 ... instances = []
> 20 ... def __init__(self):
> 20 ... if len(self.__class__.instances) == 0:
> 20 ... self.__class__.instances.append(self)
> 20 ... else:
> 20 ... raise Exception("No way jose!")
> 20 ... # to do it correct, I think getrefcount would me neccesary
> 53 >>> Singleton()
> <__main__.Singleton object at 0x403afe4c>
> 54 >>> Singleton()
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "<stdin>", line 7, in __init__
> Exception: No way jose!
> 55 >>> del Singleton.instances[0] # delete the last reference to the object
> 56 >>> Singleton()
> <__main__.Singleton object at 0x403affac>
It's not about enforcing it to be called only once, it's about
guaranteeing you always get the same instance. Here's a Singleton object
I recently wrote (it's simpler than Guido's -- I don't quite understand
why he's mucking with __dict__ and adds an init() method):
>>> class Singleton(object):
... _instance = None
... def __new__(cls, *args, **kwargs):
... if cls._instance is None:
... cls._instance = object.__new__(cls)
... return cls._instance
...
>>> a = Singleton()
>>> b = Singleton()
>>> a is b
1
>>>
> But what is the purpose of a Singleton class?
In my case it was basically a euphemism for a global variable ;-)
Just
More information about the Python-list
mailing list