Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding an objects value within a function (closure) [duplicate]

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?

like image 934
Lanaru Avatar asked Feb 16 '26 01:02

Lanaru


2 Answers

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.).

like image 112
mgilson Avatar answered Feb 18 '26 14:02

mgilson


You could do:

   x = 3
   f = lambda y=x: y
   f()
   >>> 3
   x = 7
   f()
   >>> 3
like image 34
Neal Avatar answered Feb 18 '26 15:02

Neal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!