In SML (a functional programming language that I learned before Python), I can do the following:
val x = 3;
fun f() = x;
f();
>>> 3
val x = 7;
f();
>>> 3
In Python, however, the first call will give 3 and the second one will give 7.
x = 3
def f(): return x
f()
>>> 3
x = 7
f()
>>> 7
How do I bind the value of a variable to a function in Python?
You can use a keyword argument:
x = 3
def f( x=x ):
return x
x = 7
f() # 3
Keyword arguments are assigned when the function is created. Other variables are looked up in the function's scope when the function is run. (If they're not found in the function's scope, python looks for the variable in the scope containing the function, etc, etc.).
You could do:
x = 3
f = lambda y=x: y
f()
>>> 3
x = 7
f()
>>> 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With