Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does Python evaluate a variable in a function definition

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.

like image 509
Olivier Esser Avatar asked Dec 30 '13 18:12

Olivier Esser


1 Answers

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.

like image 59
Simeon Visser Avatar answered Sep 21 '22 01:09

Simeon Visser