Change function variables from internal function in python

Good to get and print the external function variable a

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

You can also get an external array of a functions and add something

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

However, this caused some problems 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 is this happening and how can I achieve my goal (increase an integer)?

+4
source share
3 answers

Workaround for Python 2:

 def outer(): a = [1] def inner(): a[0] += 1 print a[0] 
+3
source

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

In Python 2, this is not possible.

+4
source

There is usually a cleaner way to do this:

 def outer(): a = 1 def inner(b): b += 1 return b a = inner(a) 

Python allows a lot, but non-local variables can usually be considered "dirty" (without going into details here).

+3
source

All Articles