Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we access inner function outside its scope of outer function in python using outer function?

Just for the sake of curiosity I wanna know this..
I know scope of inner function is limited to outer function body only, but still is there any way so that we can access the inner function variable outside its scope or call the inner function outside its scope ?

In [7]: def main():
   ...:     def sub():
   ...:         a=5
   ...:         print a
   ...:         

In [8]: main()

In [9]: main.sub()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/home/dubizzle/webapps/django/dubizzle/<ipython-input-9-3920726955bd> in <module>()
----> 1 main.sub()

AttributeError: 'function' object has no attribute 'sub'

In [10]: 
like image 838
NIlesh Sharma Avatar asked Jul 24 '12 07:07

NIlesh Sharma


People also ask

Can Python inner function access outer variable?

Python Inner Functions or Nested Functions can access the variables of the outer function as well as the global variables. The inner functions variable has a local scope that is limited only to that function. Inner Functions variables can't be accessed at the outer function scope.

How do you access the inner function in Python?

A function which is defined inside another function is known as inner function or nested functio n. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. This process is also known as Encapsulation .

Can you call a nested function outside a function?

Nested function is private to containing function Only the containing function can access the nested function. We cannot access it anywhere outside the function. This is because the inner function is defined in the scope of the outer function (or containing function).

How do you use the inside function variable in an outside function?

To access a variable outside a function in JavaScript make your variable accessible from outside the function. First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function.


4 Answers

>>> def main():
...     def sub():
...         a=5
...         print a
... 
>>> main.__code__.co_consts
(None, <code object sub at 0x2111ad0, file "<stdin>", line 2>)
>>> exec main.__code__.co_consts[1]
5
like image 119
John La Rooy Avatar answered Oct 05 '22 05:10

John La Rooy


You can if you return the inner function as a value

>>> def main():
...     def sub():
...         a = 5
...         print a
...     return sub
...
>>> inner = main()
>>> inner()
5

or you can attach it to main as a property (functions are objects after all):

>>> def main():
...     def sub():
...         a = 5
...         print a
...     main.mysub = sub
...
>>> main()
>>> main.mysub()
5

but you better document your very good reason for doing this, since it will almost certainly surprise anyone reading your code :-)

like image 43
thebjorn Avatar answered Oct 05 '22 04:10

thebjorn


No, you can't. The inner function is not an attribute of the outer function.

The inner function only exists after its def statement is executed (while the outer function is executed), and it stops to exist when the function exits.

You could return the inner function, of course.

like image 26
Reinstate Monica Avatar answered Oct 05 '22 04:10

Reinstate Monica


A function is just another object in Python and can be introspected.

You can get the outer function body at runtime and parse/eval it to make the function available in the current namespace.

>>> import inspect
>>> def outer():
        def inner():
            print "hello!"
>>> inspect.getsourcelines(outer)
([u'def outer():\n', u'    def inner():\n', u'        print "hello!"\n'], 1)

Not really the same thing as calling outer.inner(), but if you are not making the inner function explicitly available outside the scope of the outer function, I guess it is the the only possibility.

For example, a very naive eval attempt could be:

>>> exec('\n'.join([ line[4:] for line in inspect.getsourcelines(outer)[0][1:] ]))
>>> inner()
hello!
like image 38
Paulo Scardine Avatar answered Oct 05 '22 06:10

Paulo Scardine