Search code examples
pythonsetnested-functionpython-nonlocal

Python inner function sets vs nonlocal


I believe I know the answer to this, but wanted to double-check because I find this a bit confusing.

def outerFunc():
    mySet = set()
    a = 0
    def innerFunc():
        mySet.add(1)
        mySet.add(2)
        a = 7
    innerFunc()
    print(mySet) # {1, 2}
    print(a) # 0

Here, if I want to change the value of a, I need to use nonlocal. The fact that the set changes is just because sets are passed by reference? So, in an inner function we have access to the values of the outer function's variables, but cannot modify them unless they're references?


Solution

  • You can check the python document

    In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

    So if you assigned a variable and the variable without global just affects the local. For example, if you assigned value to mySet, then it also does not change.

    def outerFunc():
        mySet = set()   
        def innerFunc():
            mySet = {1}
            mySet.add(2)
        innerFunc()
        print(mySet)  # ''