Scope of variables in nested functions

Viewed 36

Code extract is below, I am trying to modify a variable in a nested function, I started out by practising modifying in a normal function and using the keyword 'global', however in a nested function I can only make it work by putting in global (highlighted in comment), but by doing this I am expanding the scope of the 'y' var outside the function bar, to the main program which is not what I want.

I only want the inner function foo to be able to see and modify 'y' but I do not want to make 'y' available to the main program.

Note I have already seen this post Using a global variable inside a function nested in a function in Python, however the question remains.

Thank you.

# accessing x outside scope is okay
x = 5
def bar():
    print(x)    
bar()

# modifying x outside scope needs global 

x = 5
def bar():
    global x
    x = x+5
    print(x)

# now original reference has been changed as  well. 
bar()
print(x)   

# scope within nested functions 

def bar():
    global y ## why is this needed?
    y = 5 
    print(f'y before foo called (): {y}')
    def foo():
        global y 
        y = y + 1 
        print(f'y in foo called (): {y}')

    foo()
    print(f'y after foo called (): {y}')

bar()
print(f'y outside function foo called (): {y}')
1 Answers

Your solution works because global y makes y global. It is now available in all functions, including in nested functions. Instead, you probably want to declare nonlocal y inside foo() and remove all the global y declarations. This allows you to assign a value to y in the nested scope without exposing it to other functions.

Related