Search code examples
pythonfunctionscoping

Inner Functions captures outside variable?


def outer_function(some_function):
    def inner_function(arg):
        print arg
    return inner_function

def function_2(a):
    return a

x = outer_function(function_2)
x(3)

My issue here is that how is inner_function able to capture the argument which I passed to x which is 3. How is the inner function able to capture an outside function argument?


Solution

  • The inner function isn't capturing an outer function argument.

    x = outer_function(function_2)
    

    x is now a reference to inner_function, which takes in an argument and prints it.

    x(3)
    

    This is the same as inner_function(3), which just prints 3 so 3 is printed.