Mohd Ali
Mohd Ali

Reputation: 311

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.

Upvotes: 4

Views: 147

Answers (3)

kmario23
kmario23

Reputation: 61375

We are defining the functions child1() & child2() and returning the references to these functions outside the nested scope (here, parent). So, every time you call the parent function, new instances of child1 & child2.

And we want these references only.That's why there's no parenthesis. If you add parenthesis, then the function will get called.

Upvotes: 0

sirfz
sirfz

Reputation: 4277

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()

Upvotes: 6

Eric
Eric

Reputation: 97601

return func()  # returns the result of calling func
return func    # returns func itself, which can be called later

Upvotes: 3

Related Questions