Python how to use (variables inside function F1) inside function (F2 which is inside F1)

Viewed 340
def F1():
    myvar = 1
    myArrayVar = []

    def F2():
        global myvar, myArrayVar # this will be changed by F2()
        myvar = 2
        myArrayVar.append(myVar)
        print(myvar)
    F2()

F1()

So I have a function inside a function. Since F2() is recursive, I have to store variables outside.

In C I would separate both or pass pointers, in Java I would create objects. But is there anyway in Python that allows me to do this quickly without much changes? I don't want to use global variables, myvar needs to be kept within the context of F1()

Thank you.

2 Answers

You can use nonlocal variables:

def F1():
    myvar = 1
    myArrayVar = []

    def F2():
        nonlocal myvar, myArrayVar  # this will be changed by F2()
        myvar = 2
        myArrayVar.append(myvar)

    F2()
    print(myvar)
    print(myArrayVar)

F1()
2
[2]

Actually only myvar needs to be declared a nonlocal variable here. myArrayVar is just a closure variable, since you don't rebind the name it needs no special treatment.

def F1():
    myvar = 1
    myArrayVar = []

    def F2():
        nonlocal myvar  # allows changes to myvar to be seen by the outer scope
        myvar = 2
        myArrayVar.append(myvar)
        print(myvar)
    F2()

F1()
Related