Search code examples
pythondynamicvariable-assignment

Dynamic Assignment of Variables from One File in Another File [Python]


I need to dynamically assign variables from one file in another file. This was attempted by doing the following. In file1.py:

var1 = 1
var2 = 2

Then in file2.py:

 import file1

 Class File2
      def assign2(self, varName, val)
           ...
           (do stuff)
           ...
           setattr(file1, varName, val)
           print(str(getattr(file1, varName))) -> 3, 4

      def assign1(self)
           self.assign2("var1", 3)
           self.assign2("var2", 4)
           print(str(getattr(file1, "var1"))) -> 1
           print(str(getattr(file1, "var2"))) -> 2

If I simply call file1.var1 = 3 anywhere in file2.py then the update occurs, but for some reason using dynamic assignment with setattr does not. Any help is appreciated.


Solution

  • I've reworked my code so that I don't have to do dynamic assignments, but for future reference, exec() worked, although its dangerous:

    def assign2(self, varName, val)
           if isinstance(val, (list, np.ndarray, tuple)):
                br = "[]"
                if isinstance(val, tuple):
                     br = "()"
                s = f"file1.{varName} = " + br[0]
                for i in range(len(val)):
                     s += f"{val[i]},"
                s += br[1]
                exec(s)
           else:
                exec(f"file1.{varName} = {val}")