According to this question I thought that I had understood the closure concept in a singleton pattern.
This is what works:
def singleton(cls):
instances = {}
print instances # control the state of instances
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class cls(object):
pass
@singleton
class abc(object):
pass
Then I thought that a dictionary would be too much as there is only one instance in the instances dictionary per class. So if if say a = abc()
and c = cls()
and then abc()
and cls()
again, there will be two different dictionaries printed, which is perfectly alright and the singleton works.
So I wanted to use a single variable instead of a dictionary:
def singleton(cls):
instance = None
def get_instance(*args, **kwargs):
if instance is None:
instance = cls(*args, **kwargs)
return instance
return get_instance
But this lead to:
<ipython-input-22-2961f5b89daf> in get_instance(*args, **kwargs)
2 instance = None
3 def get_instance(*args, **kwargs):
----> 4 if instance is None:
5 instance = cls(*args, **kwargs)
6 return instance
UnboundLocalError: local variable 'instance' referenced before assignment
Why does it break? I only wanted to use a single variable instead of a whole dictionary, one works and one causes an assignment error.