singleton decorator

r.grimm at science-computing.de r.grimm at science-computing.de
Thu Mar 27 18:06:56 CET 2008


Hallo,
playing with the decorators from PEP 318 I found the elegant singleton
decorator.

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class A: pass

class B: pass

a1=A()
a2=A()
a3=A()
b1=B()
b2=B()
b3=B()

for i in ((a1,b1),(a2,b2),(a3,b3)):
    print id(i[0]),id(i[1])

But I always get a syntax error declaring class A as singleton.

>>> reload ( decorator)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "decorator.py", line 27
    class A: pass
        ^
SyntaxError: invalid syntax

What's the problem with this code because it's only copied for the PEP
318?
It doesn't work with python 2.4 and python 2.5.

Greetings Rainer



More information about the Python-list mailing list