1

Suppose someone wants to make a lambda function, and they want everything in the lambda function, except for the input arguments, to be treated like a function's local variables. How would they accomplish that? By saying that the variables are "local," I mean that there is no access to those variables from outside of the lambda function.

Code

right = 5

demo_lamb = lambda left : print("INSIDE  LAMB left == ", left, ",", "right == ", right)

for lt in range(0, 5):
    demo_lamb(lt)
    right = 100*lt + 99
    print("OUTSIDE LAMB              right == ", right)

Printed Output

INSIDE  LAMB left ==  0 , right ==  5
OUTSIDE LAMB              right ==  99
INSIDE  LAMB left ==  1 , right ==  99
OUTSIDE LAMB              right ==  199
INSIDE  LAMB left ==  2 , right ==  199
OUTSIDE LAMB              right ==  299
INSIDE  LAMB left ==  3 , right ==  299
OUTSIDE LAMB              right ==  399
INSIDE  LAMB left ==  4 , right ==  399
OUTSIDE LAMB              right ==  499       

Desired Output

INSIDE  LAMB left ==  0 , right ==  5
OUTSIDE LAMB              right ==  99
INSIDE  LAMB left ==  1 , right ==  5
OUTSIDE LAMB              right ==  199
INSIDE  LAMB left ==  2 , right ==  5
OUTSIDE LAMB              right ==  299
INSIDE  LAMB left ==  3 , right ==  5
OUTSIDE LAMB              right ==  399
INSIDE  LAMB left ==  4 , right ==  5
OUTSIDE LAMB              right ==  499

How do we "freeze" the value of all of the variables inside of a lambda function (except the input arguments) to be what they were when the lambda function was created?

One Failed Solution

Importing copy and replacing right inside the lambda function with copy.deepcopy(right) makes no difference to the output whatsoever.

Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
  • you have to bind the variable to the lambda function. – Jean-François Fabre Oct 09 '17 at 19:17
  • 2
    If you are using `some_var = lambda ` you shouldn't be using a `lambda` in the first place, it defeats the **only advantage** which is that a `lambda` is anonymous. – juanpa.arrivillaga Oct 09 '17 at 19:18
  • And the problem is that `right` isn't a local variable, it is a *free variable* closed over the function. The problem is that Python has lexical scoping, so `right` always refers to the `right` in the global scope. The best thing to do is just to make it a parameter. Also, this has nothing to do with `lambda` functions, but **all functions work this way** – juanpa.arrivillaga Oct 09 '17 at 19:21

1 Answers1

1

The usual trick, which dates to before the introduction of closures at all, is to use "optional parameters":

demo_lamb = lambda left, right=right: print("INSIDE  LAMB left == ", left, ",", "right == ", right)

Default arguments are evaluated when the function is defined, which is exactly what you want.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76