0

I have run into a script concerning namespace and scope in Python, for which I can’t figure out how this script runs because of its mixed and recondite usage of these two concepts. Here is the code:

j, k = 1,2
def proc1():
       j, k = 3, 4
       print “ j == %d and k == %d” % (j, k)
       k = 5

def proc2():
       j = 6
       proc1()
       print “ j == %d and k == %d” %(j , k)

k = 7
proc1()
print “ j == %d and k == %d” % (j, k)

j = 8
proc2()
print “ j == %d and k == %d” % (j, k)

I reckon the output of this script should contain only four print expression, but it turns out to be five when running it . Besides, the value of j and k in each line is also quite different from what I have expected. Could someone explain how this runs?

Sincere gratitude offered if you could also elaborate on the namespace and scope in these chunk of code. Besides, here is the output when I run it from my computer which currently is equipped with Python 2.7.14. output result

3
  • It prints five output because in the definition of proc2, there is a line 'proc1()' For the variables, the j,k in your functions are local to your functions, it is as if you called them j_1, k_1 and j_2, k_2 and their livenesses are bound to the function scope Commented Dec 18, 2017 at 8:51
  • @BadMiscuit thanks a lot! In that way, what is the value of j and k after the second function- proc2? Sorry for this late reply. Commented Dec 19, 2017 at 8:11
  • If you are talking about the firsts j and k (lets say j_0 and k_0) it should be j = 8 and k = 7 (as in your output) because your functions don't modify these values (they create temporary variables) Commented Dec 19, 2017 at 8:48

1 Answer 1

0

Small outline explaining how your variables live

Scope and liveness

EDIT : The part 'we can reuse j_1 because the previous j_1 and this one never live together' is actually not totally accurate, because in proc2 you call proc1 so they do live together. So blue j_1 (j in proc2 is actually j_2. I changed the outline.

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

3 Comments

Wow, your explanation is awesome! This flowchart completely enlightens me! I couldn’t thank you enough for your detailed and professional assist. Thanks again!
I still have one question, though. Why isn’t k altered in pro1 after executing this function? Aka, why does the “k = 5” in proc1 serve no purpose?
@user8542107 Because k = 5 in proc1() is similar to k_1 = 5, you are assigning a new value to the variable you defined in the innermost scope

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.