singleton objects with decorators

Steven Bethard steven.bethard at gmail.com
Mon Apr 11 14:49:53 EDT 2005


Uwe Mayer wrote:
> Hi,
> 
> I've been looking into ways of creating singleton objects. With Python2.3 I
> usually used a module-level variable and a factory function to implement
> singleton objects.
> 
> With Python2.4 I was looking into decorators. The examples from PEP 318
> http://www.python.org/peps/pep-0318.html#examples
> 
> don't work - AFAIK because:
> - you cannot decorate class definitions (why was it left out?)
> - __init__ must return None
> 
> 
> However, you can use the decorator:
> 
> def singleton(f):
>     instances = {}
>     def new_f(*args, **kwargs):
>         if (f not in instances):
>             instances[f] = f(*args, **kwargs)
>         return instances[f]
>     new_f.func_name = f.func_name
>     new_f.func_doc = f.func_doc       
>     return new_f
> 
> with a class that overwrites the __new__ methof of new-style classes:
> 
> class Foobar(object):
>     def __init__(self):
>         print self
> 
>     @singleton
>     def __new__(self):
>         return object.__new__(Foobar)
> 
> Is this particularly ugly or bad?

Seems a little confoluted.  Why can't you just use something like:

class Singleton(object):
     def __new__(cls, *args, **kwargs):
         try:
             return cls.__instance__
         except AttributeError:
        	    instance = cls.__instance__ = super(Singleton, cls).__new__(
                 cls, *args, **kwargs)
             return instance

class Foobar(Singleton):
     def __init__(self):
         print self

?

STeVe



More information about the Python-list mailing list