On 12/06/2016 00:44, Marcin Rak wrote:
Hi to all.
I have the following file named Solver.py:
*****************************************
from Test import some_function, my_print
from Test import test_var
some_function()
my_print()
print(test_var)
*****************************************
and I have the following Test.py:
*****************************************
test_var = 5
def some_function():
global test_var
test_var = 44
print("f {0}".format(test_var))
def my_print():
print(test_var)
*****************************************
Would you believe it that when I run Solver.py I get the following output:
f 44
44
5
So my question is, how the heck is it possible that I get 5 as the last value
printed? the global test_var (global to Test.py) I set to 44 when I ran
some_function()??? does anyone have a clue they could throw my way?
I was puzzled too. Apparently importing stuff using 'from':
from Test import a,b,c
is equivalent to:
import Test
a = Test.a
b = Test.b
c = Test.c
which I hadn't been aware of. Then the link between a and Test.a (eg.
Test.test_var) is broken (unless Test.a is something like a list so both
still refer to the same data. But assignment to either - not an in-place
mod - will break the connection).
Your code could be rewritten as:
from Test import some_function, my_print
import Test
some_function()
my_print()
print(Test.test_var)
Anyway, it shows Python doesn't have true cross-module globals.
--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list