Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

python - Importing and changing variables from another file

Okay...

I have searched and searched looking for an answer that directly answers my question, but have had no success. My problem is pretty straight forward and I honestly thought there would have been a more direct answer out there. Please keep in mind I am still relatively new to the language, and am still learning.

So I will use fileA and fileB as my two files, and x as my example variable. Variable x is contained in fileB. How do I go about importing variable x into fileA, then change x to another value via raw_input, and then have the variable x update in fileB with the new value?

I'm not sure if this is even possible, but I would sure like to think so. I am using python 2.7.11, thank you in advanced.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...