0

I have searched a lot in different forums including Using global variables between files in Python? and couldn't find any proper answer for my question though there are some topics discussing about global variable and multiple files. I created three dummy codes to explain my question.

globalss.py

test_value = [0]

test.py

from globalss import *
def datagen():
  global test_value
  test_value = [100]
  print('test_value from datagen', test_value)
datagen()
def valchange(x):
  global test_value
  test_value = [x]
  print('test value in val change', test_value)
valchange(1000)

testing.py

from test import *
from globalss import *
print('test_value from testing', test_value)
valchange(22222)
print('test_value from testing', test_value)

testing.py is the file i ran as main.

output

test_value from datagen [100]
test value in val change [1000]
test_value from testing [0]
test value in val change [22222]
test_value from testing [0]

Regardless of operations applied on test_value, testing.py has 0 as its value. So basically from this test codes what i understood is, a module will get the value for a global variable when it is imported. After that whatever happens to that variable from other files, it would not get reflected in that particular module.

All the answers i found from another pages are talking about initializing the variable in a common file and import that file in different modules. As i have shown in the example, that will import the value. but once imported, changes made after that in other files would populate in current file.

My question is, is there a way to share global variables across different file where the values changes will be reflected in all the files.

10
  • 1
    Please edit your question and include the output as text. Commented Mar 11, 2016 at 9:55
  • I couldn't understand how this question become the duplicate of what jonrsharpe pointed. I have tried the solutions given in that page as well. That solutions are right. But not an answer for my question. @jonrsharpe Commented Mar 11, 2016 at 10:05
  • Then please edit the question to clarify how it's different. Commented Mar 11, 2016 at 10:08
  • @jonrsharpe. yes i did. :) Commented Mar 11, 2016 at 10:12
  • Why don't you mutate the shared variable, e.g. test_value[0] = 100, rather than replacing it with test_value = [100]? Commented Mar 11, 2016 at 10:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.