Can we access an internal function outside its external function in python using an external function?

Just for the sake of curiosity, I want to know this.
I know that the scope of an inner function is limited only by the outer body of the function, but is there any way 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]: 
+4
source share
5 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 
+6
source

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 the main one as a property (functions are still objects):

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

but you better document your very good reason for this, as this will almost certainly surprise anyone who reads your code :-)

+4
source

A function is another object in Python and can be introduced.

You can get the external organ of the function at run time 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) 

This is actually not the same as calling external.inner (), but if you are not making the inner function explicitly accessible outside the scope of the outer function, I think this is the only possibility.

For example, a very naive attempt at eval might be:

 >>> exec('\n'.join([ line[4:] for line in inspect.getsourcelines(outer)[0][1:] ])) >>> inner() hello! 
+1
source

No, you can’t. An internal function is not an attribute of an external function.

An internal function exists only after the execution of its def statement (during the execution of the external function), and it ceases to exist when the function completes.

Of course, you could return to execute an internal function.

0
source

An internal function is just a local variable, just like any other, so the same rules apply. If you want to access it, you must return it.

0
source

All Articles