Lin Ma Lin Ma - 1 month ago 4x
Python Question

Python 2.7 global variable issue

Using Python 2.7. Tried to import a global variable

, in
, but return result is
in below program in
, why
is not returned? Thanks.,

counter = 0

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

from testlib import Foo
from testlib import counter

f = Foo()

g = Foo()

print counter # output is 0 other than 2


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