How do I access a variable inside a nested function from another function?

Issue

Let’s say I have a code snippet like this :

def z():
    def y():
        v = 10
def x():

and inside function x I want to access variable v. How do I do that in simplest way possible?

Solution

Here’s a complicated approach but kinda works. I wouldn’t recommend using this in actual code though.

def z():
    def y():
        y.v = 20
    y.v = 10
    return y

def x():
    y = z()

    print(y.v)
    # 10
    y()
    print(y.v)
    # 20

x()

Answered By – rv.kvetch

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published