In this answer a singleton decorator is demonstrated as such
def singleton(cls):
instances = {}
def getinstance():
print len(instances)
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
but instances
is 'local' to each class that is decorated, so I tried to be more efficient and use
def BAD_singleton(cls):
instances = None
def getinstance():
if instances is None:
instances = cls()
return instances
return getinstance
@BAD_singleton
class MyTest(object):
def __init__(self):
print 'test'
However, this gives an error
UnboundLocalError: local variable 'instances' referenced before assignment
when m = MyTest()
is called
I think I understand which this should not work (as the assignment to instances will be local and be lost between calls), but I do not understand why I am getting this error.