Search code examples
python-2.7scopenamespaces

Namespace and scope in Python


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


Solution

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