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
Let's go into little deep and explore it :
You can do this via three methods :
Just return the nested function from main function so return will become the caller of nested function:
output:
Look above example , Main function is not accepting any parameter but nested function have one parameter so here i directly pass the argument to nested function.
You can try this little hacky thing :
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 outsidefunc1()
, simply definefunc2()
at an appropriate outer scope.One way that you could do it is to pass a parameter to
func1()
indicating that it should invokefunc2()
:but since that requires modification to the existing code, you might as well move
func2()
to the same scope asfunc1()
.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 functionfunc2()
. Finally call it withexec()
:To generalise, if you had multiple nested functions in an arbitrary order and you wanted to call a specific one by name: