0
votes

I am getting getting UnboundLocalError: local variable referenced before assignment error while trying to run this code. As per LEGB rule this should run fine.

def xyz():
    count = 1
    def xyz_inner():
        count += 1
        print count
    xyz_inner()
    print count
2
eli.thegreenplace.net/2011/05/15/… Im sure there is a duplicate somewhere here - jamylak
whats your python version? - kasravnd
possible duplicate of UnboundLocalError in Python - fredtantini

2 Answers

0
votes

see unbound local error

def xyz():
    count = 1
    def xyz_inner():
        count += 1
        print count, locals()
    xyz_inner()
    print count

print hasattr(globals, 'count')
print hasattr(xyz, 'count')

>>> 
False
False

Define variable in any mutable object like dict or list(uses same reference) and update it using augmented assignment.

it works:-

def xyz():
    count = {'value': 1}
    def xyz_inner():
        count['value'] += 1
        print count['value'],
    xyz_inner()
    print count

xyz()

see python closure for nonlocal in python2.7

1
votes

The issue here is that the count in the inner function is bound by an (augmented) assignment statement, and is therefore regarded as local to xyz_inner(). Consequently, the first time the code attempts to execute count += 1 the (local) variable count has not previously been assigned, and so it is indeed an unbound local.

Use of nonlocal count inside xyz_inner() should rectify that problem by telling the interpreter you want to use xyz()'s count rather than creating a local.