I have three files: bar.py
, foo.py
, and main.py
.
# bar.py
import numpy as np
global y
x=0
y=0
z=np.array([0])
# foo.py
from bar import *
def foo():
x=1
y=1
z[0]=1
# main.py
from foo import *
from bar import *
print(x,y,z)
# 0 0 [0]
foo()
print(x,y,z)
# 0 0 [1]
Question: Why did x
and y
not change their values while z
did change value of its element? And, how should I write so that I can change values of x
and y
, which can also be accessible from other files?
Normally I'd never write in this fashion, which was forced when translating an archaic FORTRAN77
program into python
.
The original code heavily uses common blocks and includes, so basically I cannot trace the declarations of all variables. But still I wanted to preserve the original style of the code, so I tried to make a "global variables module", whose variables can be modified from any part of the program.
Back to my question, my guess is that numpy.ndarray
is just pointer, and we do not change the value of a pointer, so z
has changed. But even then the behavior of z
seems very dangerous, that I cannot trust z
to be shared as a global variable and its value is the same across all files. Who knows that z
in main
and foo
are pointing the same memory sector?
Moreover, how can I make some variables truly global? Actually when I tried to translate that FORTRAN program, I tried to make class and instances of them, then pass the instance over the arguments of the function, then I realized that requires modifying the code tremendously.
What can I do?