Why not use parentheses for return functions inside functions in Python?
I am reading this tutorial and there is an example in the Returned Functions section , for example:
def parent(n):
def child1():
return "Printing from the child1() function."
def child2():
return "Printing from the child2() function."
if n == 10: return child1
else: return child2
The author mentions that the returned functions should not have parentheses in them, but without a detailed explanation. I believe this is because if the parentheses are added then the function will be called and somehow the thread will be lost. But I need a better explanation to get a good understanding.
source to share
If you add ie parentheses to the return function ()
, then you will return the return value of this function (i.e. the function will be executed and its result will be returned). Otherwise, you return a reference to that function that you can reuse. I.e
f = parent(1)
f() # executes child2()
source to share
We define functions child1()
and child2()
and return references to those functions outside of the nested scope (here, parent). This way, every time you call the function parent
, new instances of child1
and appear child2
.
And we only want these links. Therefore, there are no parentheses. If you add parentheses, the function will be called.
source to share