6

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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3
p=4          #you are setting global p to 4
def g():
    return p
p=5          #you are setting global p to 5
print g()    #you are printing the result of g, which is not setting any value;

so 5 is printed; but here:

def make_fun():
    p=5          #you are setting local p to 5
    def f():
        return p
    return f

f=make_fun()
p=6              #you are setting global p to 6
print f()        #you printing the result of a function in f, which is getting the local p

so local p= 5 is printed;

hope i understood you right!

Comments

1

It's not a question of when evaluation takes place. In both of your examples, p is evaluated when the function is called. The real question is when does that variable get declared.

In your first example, p is declared outside of the function and therefore has global scope. Any changes to p impact it wherever it it referenced.

In your second example, you are declaring another variable p inside the function. This is local to the function and not impacted by any code outside of the function. Even if you then go ahead and declare another global p as you do in the line after f=make_fun(), this global variable is overridden within the function by the local variable.

As an experiment, try printing p after you print f() and you'll see that it's value will be 6 as you assigned it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.