Importing and changing variables from another file

前端 未结 2 940
暖寄归人
暖寄归人 2020-12-09 04:35

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 ho

相关标签:
2条回答
  • 2020-12-09 05:15

    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.

    0 讨论(0)
  • 2020-12-09 05:22

    If you mean constant variable, in 90% of situations, it means bad architecture of a program, because it may be implemented easier.

    One of a possible way could be:

    create some functions in both of files with input parameter and execute them and play with value.

    for example:

    fileA.py

    from fileB import testB
    TEST_VAL = 5
    
    def testA(val):
        TEST_VAL += 10
        result = testB(TEST_VAL)
        # play with changed TEST_VAL
    

    fileB.py

    def testB(val):
        # do something
        return val ** 2
    
    0 讨论(0)
提交回复
热议问题