I have defined a function within another function in python and now I would like to call the inner function. Is this possible, in python?
How do I call func2
from func3
?
def func1():
def func2():
print("Hello!")
def func3():
# Enter code to call func2 here
You can't, at least not directly.
I'm not sure why you would want to do that. If you want to be able to call func2()
from outside func1()
, simply define func2()
at an appropriate outer scope.
One way that you could do it is to pass a parameter to func1()
indicating that it should invoke func2()
:
def func1(call_func2=False):
def func2():
print("Hello!")
if call_func2:
return func2()
def func3():
func1(True)
but since that requires modification to the existing code, you might as well move func2()
to the same scope as func1()
.
I don't recommend that you do this, however, with some indirection you can reach into the func1()
function object and access it's code object. Then using that code object access the code object for the inner function func2()
. Finally call it with exec()
:
>>> exec(func1.__code__.co_consts[1])
Hello!
To generalise, if you had multiple nested functions in an arbitrary order and you wanted to call a specific one by name:
from types import CodeType
for obj in func1.__code__.co_consts:
if isinstance(obj, CodeType) and obj.co_name == 'func2':
exec(obj)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With