Sharing values through global variables in files is generally not considered as a correct design. It is much more powerful and flexible to create a base class storing the shared data and a arbitrary number of derived classes that need access to this shared data. Here is a skeleton for that pattern:
class Shared(object):
shared = [0, 0] # put all shared values in a list or a dictionary
class C1(Shared):
def __init__(self):
print('C1: shared =', self.shared)
def update(self, index):
self.shared[index] += 1
print('C1: shared =', self.shared)
class C2(Shared):
def __init__(self):
print('C2: shared =', self.shared)
def update(self, index):
self.shared[index] += 1
print('C2: shared =', self.shared)
c1 = C1()
c1.update(0)
c2 = C2()
c2.update(0)
c2.update(1)
c1.update(1)
Result:
C1: shared = [0, 0]
C1: shared = [1, 0]
C2: shared = [1, 0]
C2: shared = [2, 0]
C2: shared = [2, 1]
C1: shared = [2, 2]
Of course all three classes may be in three different source files, just import
before using them
If you REALLY insist on not using the OO paradigm, the following code may fulfil your wishes:
# --------------
# shared.py
# --------------
shared = [0,0] # put all shared values in a list or a dictionary
# --------------
# C1.py
# --------------
from shared import *
print('C1: shared =', shared)
shared[0] += 1
print('C1: shared =', shared)
# --------------
# C2.py
# --------------
from shared import *
print('C2: shared =', shared)
shared[0] += 1
print('C2: shared =', shared)
The magic works from the fact that an imported file is only executed when it is imported for the first time, so the shared
variable will not be reset when shared.py
is imported the second time.