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.