On 8/3/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi, > > I have got a problem with importing global variables. For instance I have > got two files: > > # t1.py #t2.py > > counter = 1 > > def counter_adder(filenr): def show_adder(): > global counter import t1 > counter+= 1 print("adder > is %d" % t1.counter) > if filenr == 1: > show_adder() > else: > import t2 > t2.show_adder() > > def show_adder(): > print("adder is %d" % counter) > > >>counter_adder(1) > adder is 2 > >>counter_adder(2) > adder is 1 > > When I look at the outcome of two function calls I expected no differences > but much to my surprise it goes wrong when the global variable is imported. > It doesn't give the updated value but the value it get when instantiated. > Who come? What should I do to get the updated value
call: counter_adder(2) In "t2.py", you are importing a python module "t1.py". And its very logical that all the (global) variables in "t1.py" have the value which one would expect after execution of the "t1.py" otherwise. And hence you see value of counter as 1. (or in other words you are accessing two different instances of variable "counter") I would rather advice that you pass counter as a variable to the function-calls, or use a class. cheers, amit. -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list