Importing and changing variables from another file
If the "variable" you're referring to is an mutable value, what you're asking for will just work.
fileB:
my_variable = ["a list with a string in it"]
fileA:
from fileB import my_variable # import the value
my_variable.append("and another string")
After fileA
has been loaded fileB.my_variable
will have two values in it.
But, that only works for mutable values. If the variable is immutable, the code in fileA
can't change it in place, and so you'll have issues. There's no way to directly fix that, but there are many ways to work around the issue and still get at what you want.
The easiest will simply be to use import fileB
instead of from fileB import my_variable
. This lets you anything in fileB
's namespace, just by using a name like fileB.whatever
. You can rebind things in the namespace to your heart's content:
fileB:
my_variable = 1 # something immutable this time
fileA:
import fileB
fileB.my_variable = 2 # change the value in fileB's namespace
That is probably the simplest approach.
Another solution would be to put the immutable variable inside a mutable container, and then modify the container, rather than the variable. For instance, if the string "a list with a string in it"
was the value we wanted to change my the first example, we could simply assign a new value to my_variable[0]
(rather than appending).
A common way to do this is to put values into a dictionary, list or even in a class (or a mutable instance of one). Then you can import the container object and mutate it to change the value you care about.