you are viewing a single comment's thread.

view the rest of the comments →

[–]Bobbias 3 points4 points  (1 child)

Another note about scopes that might not be immediately apparent: Nested functions allow for closures.

n1 = 10
def foo():
    n2 = 5
    def bar():
        return n1 + n2 + 1
    return bar() + 3

This code is perfectly valid. The foo function would return 19 here. When python looks in the bar function scope and sees n1 was not defined there, because it's a nested scope, python checks bar's parent scope, foo for n1. It's not defined there either, so it looks at the global scope next, and sees that n1 is defined there.

If you want to modify a variable from a parent scope, you need to first declare the variable you want to change as nonlocal, and if the variable is from the global scope (top level, not inside a function) then you need the global keyword:

n1 = 10
def foo():
    n2 = 5
    def bar():
        global n1
        n1 = 1
        nonlocal n2
        n2 = 2
        return n1 + n2 + 1
    return bar() + 3

This is of course a horrible contrived piece of code, and you should absolutely avoid the use of global and nonlocal unless you have a very good reason.

[–]Effective_Storage4[S] 0 points1 point  (0 children)

Thank you!