I am confused as when does Python evaluates a variable. For example if I do:
p=4
def g():
return p
p=5
print g()
I get 5, so in the definition of g
, the variable p
remains unevaluated. It is evaluated when we call g
However if I do:
def make_fun():
p=5
def f():
return p
return f
f=make_fun()
p=6
print f()
I get 5. Why does notf
contains the unevaluated variable p
? I would like to have a clear idea as of when precisely the evaluation of variables takes place.
Python executes the code as it loads the module / script. Hence in your first example it's not "evaluated when we call g", it simply means that the latest value of p
is 5 at the time when g
is executed. Python will lookup p
and it'll return the current value (5).
In your second example p
is a local variable. That means it's not affected by p = 6
in the global scope. Or to be clear, the p
in f()
in your second example is the local variable set within make_fun()
. So that's the value you'll get back, it's not the p
at the outer (global) scope, which is a different p
.
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