2

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
  • 3
    You don't need global y in bar(). You need nonlocal y in foo() instead of global y Commented Jun 9, 2022 at 19:56

1 Answer 1

0

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.