BasavarajaMS
BasavarajaMS

Reputation: 161

How to access variable of a nested functions in python?

I need to access a variable which is set in a nested function. I'm reading this variable data from another thread. What is the best way to obtain the data without doing any scope violation?

Here is the code snippet,

class main(object):
    def sub_fun(self):
        def inner_fun(self):
            self.var = 10
        inner_fun(self)

p = main().sub_fun()

Now how to access the var attribute of p?

Upvotes: 1

Views: 3936

Answers (2)

Vimal Maheedharan
Vimal Maheedharan

Reputation: 755

class main(object):
    def sub_fun(self):
        def inner_fun(self):
          self.var = 10
p = main()

You cannot access the nested function's variable because its a closure & is accessible only to the immediate parent. var is only accessible by inner_fun. See below for a different implementation.

class main(object):
def outer_function(self):

    def inner_function(self):
        self.x = 10
        return self.x

    out = inner_function(self) # Accessing the inner function
    return out 

p = main()
q = p.outer_function() 
print(q)

If there is a need for a class object or a parent function to access a variable inside a child nested function, then the variable should be hoisted to the outer scope by returning it. Otherwise the scope of the variable will reside only in the so called child nested function.

Upvotes: 2

Mad Physicist
Mad Physicist

Reputation: 114330

The problem is that main.sub_fun returns None. There are two simple workarounds:

  1. Just store a reference to the item you create before calling the method:

    p = main()
    p.sub_fun()
    print(p.var)
    

    This is the best option in my opinion.

  2. If you really want the one line version to work, return self from sub_fun:

    def sub_fun(self):
        def inner_fun():
            self.var = 10
        inner_fun()
        return self
    
    print(main().sub_fun().var)
    

In neither case do you need to pass self to inner_fun. It will always look into the outer scope when the local name is not found. #2 shows an example of this.

Upvotes: 1

Related Questions