0

try to understand how to assign value to a variable from nested function. but it does not work. is it because when I use a = b, it consider a is local variable for nested function? then how can I assign value to the a variable from func?

def func():
    a = 0
    def nested(b):
        global a
        a = b
    nested(3)
    return a
print(func())
jacobcan118
  • 7,797
  • 12
  • 50
  • 95

2 Answers2

4

Use nonlocal to access data in the enclosing scope:

def func():
    a = 0
    def nested(b):
        nonlocal a
        a = b
    nested(3)
    return a
print(func()) # => 3

Having said this, using the global and nonlocal keywords break encapsulation and is a design antipattern that is nearly always avoidable using parameters and return statements.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • I was stuck on thinking of why global was wrong and completely blanked on swapping it to nonlocal. Better answer for sure. – MyNameIsCaleb Apr 21 '19 at 20:48
0

The reason your solution isn't working is that you're assigning your value to a in the global scope. If you would print(a) outside your outer function (and thus in the global scope) you would get the value 3.

To get your desired effect you would use nonlocal instead of global like this:

def func():
    a = 0
    def nested(b):
        nonlocal a
        a = b
    nested(3)
    return a

However a more appropriate solution would be to not mess with the scope and return the desired value from the nested function instead, and then assign it.

Glenn D.J.
  • 1,874
  • 1
  • 8
  • 19