Home > Back-end >  How do I access a variable inside a nested function from another function?
How do I access a variable inside a nested function from another function?

Time:09-24

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?

CodePudding user response:

Following is 1 way

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

    y()


def x():
    print(v)


z()
x()

Note : you have to invoke y() at least one before invoking x

CodePudding user response:

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()

CodePudding user response:

It is not possible to do that, however, to solve this, you can use a globally accessible variable like so:

globalVariable = 0
def z():
  def y():
    v = 10
    globalVariable = v
def x():
  #use globalVariable here

However do make sure you already called function y() before accessing x() so that you are getting the correct value you wanted.

  • Related