I'm learning python and I am stumbling over trying to understand how Python handles closures. I generally understand this to be a free-variable is stored in memory to be accessed long after the callee scope has expired. I am confused as to how this kind of setup is resolved.
def do_something(x):
return lambda y: y + x;
f = do_something(4);
f(4)
Here f(4) seems to use the lambda function signature instead of the do_something signature.
It returns 8, but what internally causes python to use y instead of x as the input parameter? Should I think of do_something similarly to a class definition, where f = do_something(4) is a constructor and f(4) is the actual action to take?
See this for where I first encountered this.
f(y)instead ofdo_something(y)?do_somethinghasxas a parameter while the lambda hasy.