Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When defining a lambda function with a variable inside, how to prevent changes in function when I change the variable?

Tags:

python

For example: in this code, function changes when the variable changes. I would like to learn how to prevent the change in function behaviour when i change the variable. Is there some way to only get the value of the variable instead of the variable itself? Also are there any sources where I can learn more about problems like this?

a = 5
adder = lambda x: x + a
print(adder(5)) # prints 10

a = 50
print(adder(5)) # prints 55
like image 327
Lütfullah Erkaya Avatar asked Dec 05 '25 16:12

Lütfullah Erkaya


1 Answers

Just like the equivalent function defined by a def statement (which is what you should be using, rather than assigning the result of a lambda expression to a name explicitly)

def adder(x):
    return x + a

the name a isn't looked up until the function is called.

One way to make a function that specifically computes x + 5 when a == 5 at definition time is use a default argument value:

def adder(x, a=a):
    return x + a

where the left-hand a is a new parameter (which isn't intended to be set explicitly), and the right-hand a is the value of the a in the current scope.

A better idea, though, is to define a closure, so that your function doesn't have a "hidden" parameter that can be abused.

# This is where a lambda expression does make sense: you want
# a function, but don't need to give it a name.
def make_adder(a):
    return lambda x: x + a

adder = make_adder(5)

a in adder is still a free variable, but now it refers to a variable in a scope which you don't "outside" access to after make_adder returns.

like image 135
chepner Avatar answered Dec 07 '25 06:12

chepner