Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify the function variables from inner function in python

It's ok to get and print the outer function variable a

def outer():
    a = 1
    def inner():
        print a

It's also ok to get the outer function array a and append something

def outer():
    a = []
    def inner():
        a.append(1)
        print a

However, it caused some trouble when I tried to increase the integer:

def outer():
    a = 1
    def inner():
        a += 1 #or a = a + 1
        print a

>> UnboundLocalError: local variable 'a' referenced before assignment

Why does this happen and how can I achieve my goal (increase the integer)?

like image 913
waitingkuo Avatar asked Dec 21 '22 11:12

waitingkuo


2 Answers

In Python 3 you can do this with the nonlocal keyword. Do nonlocal a at the beginning of inner to mark a as nonlocal.

In Python 2 it is not possible.

like image 73
BrenBarn Avatar answered Dec 24 '22 03:12

BrenBarn


Workaround for Python 2:

def outer():
    a = [1]
    def inner():
        a[0] += 1
        print a[0]
like image 43
codeape Avatar answered Dec 24 '22 03:12

codeape