Search code examples
pythonnested-function

nested functions calling with multiple args in python


This was the program for our test and I couldn't understand what is going on. This problem is called nested function problem.

def foo(a):
    def bar(b):
        def foobar(c):
            return a + b + c

        return foobar

    return bar


a, b, c = map(int,input().split())

res = foo(a)(b)(c)
print(res)

I have tried to debug this program but couldn't get any idea about why it is working.

Why is foo(a)(b)(c) not giving an error?

Why it is working and what it is called?


Solution

  • This is a closures concept, Inner functions are able to access variables of the enclosing scope.

    If we do not access any variables from the enclosing scope, they are just ordinary functions with a different scope

    def get_add(x):
        def add(y):
            return x + y
        return add
    
    add_function = get_add(10)
    print(add_function(5))  # result is 15