0

I want to modify a global variable in different python files, and I read about this thread: Using global variables between files?

In the above example, the global variable is a list reference so the modification of the list elements can be correctly done. However, if the global variable is, for example, a string, then it doesn't work.

In the below code, I try to modify the global variable defined in setting.py.

## setting.py
s = 'setting'

## main.py
from setting import s
import dau1
import dau2

if __name__ == "__main__":
    print(s)
    print('After mother')
    s = 'mother'
    print(s)
    dau1.dau1call()
    print(s)
    dau2.dau2call()
    print(s)

## dau1.py
from setting import s
def dau1call():
    global s
    print('After dau1')
    s = 'dau1'

## dau2.py
from setting import s
def dau2call():
    global s
    print('After dau2')
    s = 'dau2'

The result is

setting
After mother
mother
After dau1
mother
After dau2
mother

Is there any way to modify a global variable in different .py files?

Mayan
  • 492
  • 4
  • 11

2 Answers2

0

For dau1.py:

import setting
def dau1call():
    print('After dau1')
    setting.s = 'dau1' 

The original from setting import s creates a new variable s in module dau1 which holds its own reference to the string.

Michael Butscher
  • 10,028
  • 4
  • 24
  • 25
0

In the question you reference, the answers had you import setting not from settings import s. In the second case, you rebind the object referenced by settting.s to a module-scoped variable __main__.s in your main module. Both of these variables, setting.s and __main__.s reference the same object until you assign something new to __main__.s. Then these two variables are different.

There are no truly global variables. Except for some variables builtin to python, all variables are local to a module, a class or a function.

setting.py

s = 'setting'

main.py

import setting
import dau1
import dau2

if __name__ == "__main__":
    print(setting.s)
    print('After mother')
    setting.s = 'mother'
    print(setting.s)
    dau1.dau1call()
    print(setting.s)
    dau2.dau2call()
    print(setting.s)

dau1.py

import setting
def dau1call():
    print('After dau1')
    setting.s = 'dau1'

dau2.py

import setting
def dau2call():
    print('After dau2')
    setting.s = 'dau2'
tdelaney
  • 73,364
  • 6
  • 83
  • 116