Skip to content Skip to sidebar Skip to footer

Python Closure Local Variables

In this answer a singleton decorator is demonstrated as such def singleton(cls): instances = {} def getinstance(): print len(instances) if cls not in instan

Solution 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')

Post a Comment for "Python Closure Local Variables"