-1

Can someone explain the logic or syntax of function()() or function(function)()

An example: I can't seem to grasp the idea of how this actually works

func2(func1)("bye")

def func2(fn):
    print("func2")
    def func3(text2):
        print("func3")
        print(text2)
    return func3

def func1():
    print("func1")

func2(func1)("bye")

Output:

func2
func3
bye
3
  • 1
    A function can return another function. The first call, calls the first function and the second calls the function returned by the first Commented Feb 22, 2019 at 8:23
  • func2(func1)("bye") -> ("bye") is not calling a nested function but passing a parameter. Can't grasp this parameter passing Commented Feb 22, 2019 at 8:27
  • Yes, it is calling a nested function. It's unclear what you mean by "parameter passing". Commented Feb 22, 2019 at 8:38

1 Answer 1

2

A function can return another function. The first call, calls the first function and the second calls the function returned by the first.

The nested definitions are a separate concept not related to the question (about functions returning functions), since func3 exists only on the scope of func2, which may create confusion.

Here is a simpler example:

def f1(a):
    print("Function f1 called")
    print(a)

def f2(b):
    print("Function f2 called")
    print(b)
    return f1


f2(1)(2)
Function f2 called
1
Function f1 called
2
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.