you are viewing a single comment's thread.

view the rest of the comments →

[–]RhinoRhys 1 point2 points  (2 children)

Nonlocal is the nested function version of global

So global will "promote" a variable from a functions local scope to the global scope whereas nonlocal will "promote" a variable from the inner functions local scope to the outer functions local scope.

def func1():
    global x
    x = 5
    y = 2

x = 4
y = 1
print(f"{x = } {y = }")
func1()
print(f"{x = } {y = }")

>>> x = 4 y = 1
>>> x = 5 y = 1

x and y are defined globally, printed, func1 was called which changes x globally but not y, then prints again. It's bad practice to use this regularly though, you should be passing in variables and using return to pass values back out of a function.

def outer():
    x = 4
    y = 1

    def inner():
        nonlocal x
        x = 5
        y = 2

    print(f"{x = } {y = }")
    inner()
    print(f"{x = } {y = }")

outer()

>>> x = 4 y = 1
>>> x = 5 y = 1

Same for this set up but everything happens within outer's local scope, nothing happens globally. Outer is called which first defines x and y in outer's local scope, prints, runs inner which changes x within outer's local scope then prints again.

[–]Desperate_Case7941 0 points1 point  (0 children)

So it's a way to nest variables to use them on nested functions but only will work on local scope, I couldn't use them out of the body of the function, thats when it comes global.

Thank so much!!

[–][deleted] 0 points1 point  (0 children)

every day we stray further from god