Lin Ma Lin Ma - 2 months ago 23
Python Question

Python 2.7 global variable issue

Using Python 2.7. Tried to import a global variable

counter
from
testlib.py
, in
uselib.py
, but return result is
0
in below program in
uselib.py
, why
2
is not returned? Thanks.

testlib.py,

counter = 0

class Foo:
def __init__(self):
pass
def Count(self):
global counter
counter += 1


uselib.py,

from testlib import Foo
from testlib import counter


f = Foo()
f.Count()

g = Foo()
g.Count()

print counter # output is 0 other than 2

Answer

Per the Python docs:

The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope.

So, that implies that the counter you import is just a copy with a label imported into the current scope, meaning modification isn't happening on the right counter.

When you import counter, Python finds the module, takes the counter from testlib, then copies it to uselib. That copy is not modified because you're calls to Count modify the variable in testlib, not the copy you have added to the local scope by importing. This means you print the initial state of counter, but it never is modified, printing 0. To print correctly, use:

print testlib.counter