1

I would like to share a variable between files.

B.py

b_var = 'start'

def change_var():
    global b_var
    b_var = 'changed'

test.py

from proj.B import change_var, b_var

print(b_var)
change_var()
print(b_var)

The output is:

start
start

How can I get the output to be:

start
changed
lordcommander
  • 320
  • 3
  • 7

3 Answers3

2

The short answer is that as soon as you use a simple variable, you have lost. Because when you use (whatever value can be):

var = value

you do not try to change the object that var previouly refered to, but just make var point to a different object. So any other variables that pointed to the original object are not affected.

So you will have to use an attribute on a mutable object (here the module), or an element of a container. That way, the object itself will the changed and all variables pointing to that object will reflect the change. Of course if at any point of your program you have a simple variable pointing to the attribute, this one will not reflect the change.

So this would be ok:

from proj.B import change_var   # change_var will not change: we directly import it
import B

print(B.b_var)      # but we use b_var (expected to change) through another object
change_var()
print(B.b_var)
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

A solution similar to the python docs

B.py

b_var = 'start'

mod.py

import B

def change_var():
    B.b_var = 'changed'

test.py

import B
import mod
print(B.b_var)
mod.change_var()
print(B.b_var)

output

start
changed
Ceres
  • 2,498
  • 1
  • 10
  • 28
1

Because b_var is not a variable, is a reference to an immutable string.

The import sentence is copying the reference, and when change_var() runs it creates a new string and change only the reference on B module but not on test one.

pbacterio
  • 1,094
  • 6
  • 12