pythonfunctioncallbacknestedpartials

Which data do returned functions in python have acess to?


Suppose we want to create a callback function which adds two numbers arg1 and arg2. This could be done by returning a function reference like so:

def add(arg1, arg2):
   return arg1 + arg2

def partial(f, arg1, arg2):
   def wrapper():
      return f(arg1, arg2)
  
   return wrapper

callback = partial(add, 2, 4)
print(callback())

Output: 6

How does wrapper remember arg1 and arg2? What do we really return with return wrapper? It seems like not only is part of the function code returned but also its surroundings (in this case variables defined before wrapper). Otherwise there would be a NameError.


Solution

  • Answering your main question, this happens because of something called Closure in python. When you nest a function inside an enclosing function and return the nested function, the variables passed to the enclosing function are still in the scope of the nested function.

    You would often see use of closures for creating decorators in python.