Issues with importing variables file to file

Currently, I am making a battle simulator. This is a test version so this isn’t legitimate. Right now, I have 3 files.,, and Currently, has all of the smaller functions, the variables and most imports. and both import all from imports the function inside of and there’s my issue. After printing the variables, the variables are their base value from I am unable to figure out why this is that.

Repl link:

from functions import *

from functions import *
from charSelect import charSelection

while True:
A bunch of variables“””)
1 Like

After using the charSelection function in the file you can add this line of code:

from charSelect import *

This will mean that after the standard values of variables have been changed in the file, you are in the import new variable values.

1 Like

I had a similar issue in the past. When you use from functions import, you are importing the variable locallly, buy they are not linked back to their original source. Whenever define a variable like atk=100, and then you import atk into charSelect and main they will each get their own copy of atk with a value = 100.

(meaning that if you change the value, it will only change in one place).

So the main thing I recommend here is that you stop using global variables (pass the necessary data as parameters to your functions and return updated data) and create classes that holds the variables as attributes.


Yours seems to work but I do want to do want to do more experimentation with it, I’ve just started using imports to different files

I would recommend you to use what @WindLother suggested, because this way it will be easier for you to use functions imported from other files and you will not need to import variables once again.

How exactly is this done?

1 Like

When you use from functions import *, you are importing variables into the namespace of the importing module ( and, but these are essentially copies of the values at the time of import. They are not references to the original variables, so changes to them in one module do not affect the others. If modifies any of the imported variables, these changes will only be reflected within’s namespace. will still have the original values that were imported when it first ran from functions import *.

1 Like

3 good ways of getting around this:

  1. Instead of using from ... import ..., use import .... Now, your code will be able to see changes to module variables by accessing it through the module. (Btw, it is not recommended to use from ... import * because it is unclear and implicit.)
  2. Put your entire game into a class, and turn module variables into instance attributes.
  3. Similar to 1, put all your variables inside of mutable objects, then access them through the objects.

Edit: in my opinion, doing from charSelect import * in the loop is the least pythonic solution.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.