singleton decorator

R

r.grimm

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

Bruno Desthuilliers

(e-mail address removed) 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.
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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top