Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not use parenthesis on return functions inside functions in Python?

I'm reading this tutorial and under the Returning Functions part, there's an example something like below:

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 return functions should not have parenthesis in them but without giving any detailed explanation. I believe that it is because if parenthesis are added, then the function will get called and in some way the flow will be lost. But I need some better explanation to get a good understanding.

like image 376
Mohd Ali Avatar asked Aug 30 '25 17:08

Mohd Ali


1 Answers

If you add parenthesis i.e. () to the return function then you will be returning the return-value of that function (i.e. the function gets executed and its result is returned). Otherwise, you are returning a reference to that function that can be re-used. That is,

f = parent(1)
f()  # executes child2()
like image 73
sirfz Avatar answered Sep 02 '25 05:09

sirfz