singleton decorator

Pedro Werneck pedro.werneck at terra.com.br
Mon Aug 7 20:26:16 EDT 2006


On Tue, 8 Aug 2006 01:33:31 +0200
"Andre Meyer" <meyer at acm.org> wrote:

> 
> Am I missing something here? What is the preferred pythonic way of
> implementing singleton elegantly?

I think the most "elegant" is with a metaclass, since I feel like a
singleton is not just an ordinary type (and __init__ must be called only
once)... but, as "practicality beats purity", the most pythonic way is
probably using the __new__ method and inheritance.

Something like this:

>>> class Singleton(object):
...     def __new__(cls, *args, **kwds):
...             try:
...                     return cls._it
...             except AttributeError:
...                     cls._it = object.__new__(cls, *args, **kwds)
...                     return cls._it
... 
>>> class A(Singleton):
...     pass
...
>>> x = A()
>>> y = A()
>>> x is y
True

But __init__ will be called once for each time you call A, even if it's
always the same instance returned. If this is a problem, you'll need
another method to use for initialization and call it only once.

-- 
Pedro Werneck



More information about the Python-list mailing list