singleton objects with decorators

Uwe Mayer merkosh at hadiko.de
Mon Apr 11 11:26:09 EDT 2005


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?

Thanks for comments,
Ciao
Uwe     



More information about the Python-list mailing list