0
Inner function print
Hi, I would like to understand the background of the following functions and why the print function in the inner function isn’t executed: def test(): def test2(): print("check") return test2 test() Would be thankful if you could explain the process under the hood.
7 Antworten
+ 2
Hi, Ruslan Guliyev !
I suppose it is a factory function you want to create? I adjusted it a bit. It is the outer function that have to retutn the inner function.
It i a fantasic function, that have ability to preserve the state beteween calls.
First initialize the function, the in the next step call it.
def test():
def test2():
print("check")
return test2
mytest = test()
mytest()
+ 2
Hi again, Ruslan Guliyev !
That is because there is nothing to return or print in the outer function. The outer function test() just contain a defintion of another function. But no call of that function or any else function (just a def statement).
+ 2
print(1, 10 * '- ')
# You can run the inner function if you call it from inside the outer function.
def outer():
def inner():
print("check")
return inner
inner()
outer()
print(2, 10 * '- ')
# or just just call your inner function.
def inner():
print("check")
return inner
(((inner())())())()
print(3, 10 * '- ')
# or do like this:
def outer():
def inner():
print("check")
return inner
return inner
((((outer())())())())()
+ 2
def outer():
def inner():
print("check")
return inner
return inner
outer()()
# Hi, Ruslan Guliyev !
# That's because when you call outer() it return 'inner'.
# inner is a function, so you can call it, like inner(). You can't reach (call) ’inner’ direct from outside the ’outer’ function, but you can use outer to get it.
# Because ’inner’ is just a reference to the place in memory where the object is, you can assign it to a variable, like var = outer(). Now var is pointing to the same object as 'inner' does, and you can reach the inner function via 'var'. So when you call var(), it is the same as just call the inner function: inner()
# Clever, isn't it? Almost like fishing! 🎣
# But instead of assign inner to a variable var, var = outer(), and then call var via var(), you can call it direct from outer:
# outer()()
# It become the same as just calling the inner function, inner()
+ 1
Hi Per Bratthammar,
Thanks for your response!
But can you explain why print in my functions doesn’t work without moving the return statement?
+ 1
Thank you for so comprehensive answer! Per Bratthammar
Can you also please answer why in 3rd example we need to call outer()() with ()*2 times in order to print “check”?
0
Per Bratthammar, thank you a lot. It is very helpful!
Could you also please explain why following function gives an error and doesn’t return test function:
def outer():
print("outer")
def inner():
print("check")
return inner
def test():
print("test")
return test
return test
outer()()()