-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
thom747
  • 805
  • 5
  • 18
lee
  • 31
  • 4
  • 1
    A function can return another function. The first call, calls the first function and the second calls the function returned by the first – Attersson Feb 22 '19 at 08:23
  • func2(func1)("bye") -> ("bye") is not calling a nested function but passing a parameter. Can't grasp this parameter passing – lee Feb 22 '19 at 08:27
  • Yes, it is calling a nested function. It's unclear what you mean by *"parameter passing"*. – jonrsharpe Feb 22 '19 at 08:38

1 Answers1

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
Attersson
  • 4,755
  • 1
  • 15
  • 29