2

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.

2
  • 1
    A more complete @singleton. Commented Jun 21, 2012 at 17:18
  • @ephemient Thanks. That is a really useful looking page in general. Commented Jun 21, 2012 at 21:12

1 Answer 1

1

The reason for the error is python is cleverer than I am and identified that instances is made local by the assignment and does not go up-scope to find the assignment. As pointed out in the comments by @GeeTransit this is possible in python3 via nonlocal

def nonlocal_singleton(cls):
    instances = None
    def getinstance():
        nonlocal instances
        if instances is None:
            instances = cls()
        return instances
    return getinstance

@nonlocal_singleton
class MyTest(object):
    def __init__(self):
        print('test')
Sign up to request clarification or add additional context in comments.

2 Comments

It's been a while, but I'd like to point out that by adding a nonlocal instances, you can fix the error. It's raised because the function doesn't see a "declaration" or any sort before the first use of the variable. In this case, nonlocal instances would be similar to instances = some_value but some_value is the same as the one outside.
@GeeTransit Edited accordingly! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.