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

function, python, scope

Solution

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

Problem

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]: ```

Original source