Scope of Variables Within Nested Function

69 Views Asked by At

I find it rather confusing that the scope of variables within a nested function dependent on its type. Some variables must be declared as non-local variables while others do not. See the example below. Why is the statement nonlocal is required for some types of variables but not others? I would appreciate if you could share with me the documentation that elaborates on this.

class Solution:

    def testScope(self):
        
        myval = 137
        mystr = "This is a test."
        mydic = {"apple": 1, "orange":2, "grapes": 3}
        myset = {1, 3, 7}
        mylst = [3, 7, 11]
                
        def addVal(val):
            # define myval variable as non-local, otherwise it is not accessible and throw this error:
            # UnboundLocalError: local variable 'mystr' referenced before assignment
            nonlocal myval
            myval += val
            print(myval)

        def addStr(s):
            # define the mystr variable as non-local, otherwise it is not accessible and throw this error:
            # UnboundLocalError: local variable 'mystr' referenced before assignment
            nonlocal mystr
            mystr += s
            print(mystr)
            
        def addDict(key, val):
            # no need to define the mydic variable as non-local.
            mydic[key] = val
            print(mydic)

        def addSet(val):
            # no need to define the myset variable as non-local.
            myset.add(val)
            print(myset)
            
        def addList(val):
            # no need to define the mylst variable as non-local.
            mylst.append(val)
            print(mylst)

        addVal(5)
        addStr(" Another test.")
        addDict("banana", 4)
        addSet(9)
        addList(13)

0

There are 0 best solutions below