Python, how can I change the value of a variable in the parent scope?

for example: the assginment statement will declare a new local variable.

foo = 'global' def func1(): foo = 'func1' def func2(): foo = 'local variable in func2' 

Using a global declaration will use foo in the global:

 def func2(): global foo foo = 'global changed in func2' #changed the foo value in global scope 

How can I change the variable foo in the scope of func1?
Thanks for any help.

Edit:

Thanks Brandon Craig Rhodes, I finally understood your meaning.

If more than 3 areas are nested, I can save the variable in the list.

 foo = ['global', 'function1', 'function2'] def func1(): foo[1] = 'func1' def func2(): foo[2] = 'func2' foo[1] = 'func1 modified in func2' 

I just use a global variable.


therefore, if two functions are nested, we can use

 nonlocal foo 

and

 global foo 

if there are more than three functions nested,
and each function uses variables in the scope of other functions,
why don't we declare a global list variable?
Thank you for your help!!!

+7
source share
2 answers

In Python 3, I believe you can use the nonlocal keyword to get permission to change a variable in a non-global scope. In Python 2, you cannot reassign foo in a closing area; instead, set foo to be a mutable object, such as a list [] , and then insert the value you want to keep in the list:

 def func1(): foo = [None] def func2(): foo[0] = 'Test' 
+8
source

In python 3.0 and above, you can use a non-local keyword.

+4
source

All Articles