Deep Vasoya
Deep Vasoya

Reputation: 91

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?

Upvotes: 1

Views: 355

Answers (2)

funnydman
funnydman

Reputation: 11396

Everything in Python is an object, and functions as well, so you can pass them as arguments, return them, for example:

def inc(var):
    return var + 1


def my_func():
    return inc


my_inc = my_func()
print(my_inc) # <function inc at ...>
print(my_inc(1)) # 2

Moreover it's closed to decorator's concept:

def log_this(func):
    def wrapper(*args, **kwargs):
        print('start', str(args))
        res = func(*args, **kwargs)
        return res

    return wrapper


@log_this
def inc(var):
    return var + 1


print(inc(10))

Upvotes: 1

Msv
Msv

Reputation: 1371

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

Upvotes: 1

Related Questions