Search code examples
pythonfunctionclosures

How to use returned result from inner function as a parameter in the outer function?


I have a question regarding how to use the returned result from the inner function as a parameter in the outer function.

I tried the following code, but the result was not what I expected:

def outer_function(a,b):
    def inner_function(c):
        inner_result = c * 100
        return inner_result 
    return inner_function 
    outer_result = a * b * inner_result 
    return outer_result

some_func = outer_function(10,9)
some_func(9)

I expected the result from the some_func(9) as 9 * 100 * 10 * 9 = 81000; instead, the result turned out to be 900.

I am wondering what I did wrong and how I can use the inner_result as a parameter in the outer_function?


Solution

  • outer_function (like all functions) can only return a single value, yet you're attempting to return both the inner_function, and the outer_result. The first return ends the function, leading to erroneous behavior.

    If you don't want to incorporate the outer_result calculation into inner_function (I'd just do that), you could wrap it in another function that carries out the calculation. That could be done via a lambda, or another full def:

    def outer_function(a,b):
        def inner_function(c):
            inner_result = c * 100
            return inner_result
        return lambda c: a * b * inner_function(c)
    

    or

    def outer_function(a,b):
        def inner_function(c):
            inner_result = c * 100
            return inner_result
        def second_inner_function(d):
            return a * b * inner_function(d)
        return second_inner_function
    

    Although, again, the a * b * calculation should likely just be added into inner_function unless for conceptual reasons you really wanted to keep it separate.