singleton decorator

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Mar 27 13:18:37 EDT 2008


r.grimm at science-computing.de a écrit :
> 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
> 
(snip)


> 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.

A pep is a proposal, not a feature documentation. As written in pep318, 
class decorators have not been implemented so far. They'll be 
implemented in 2.6 (more exactly: they are implemented in 2.6, but 2.6 
is still alpha so far).




More information about the Python-list mailing list