1

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())
2
  • 2
    ideally, return from the nested function, and assign. dont mess with scopes if you dont have to. Commented Apr 21, 2019 at 20:46
  • 2
    Use nonlocal instead of global, that being said I agree with @ParitoshSingh that you should return not assign the value unless you are working with something like a decorator. Commented Apr 21, 2019 at 20:46

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I was stuck on thinking of why global was wrong and completely blanked on swapping it to nonlocal. Better answer for sure.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.