1

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?

2
  • You should break the problem down into smaller parts. For example, what would f be if you write: f = foo(a)? Commented Aug 9, 2022 at 13:07
  • frist check type( foo(a) ) - you get function bar and you can add (...) to execute it. Commented Aug 9, 2022 at 14:13

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.