Currently, I am making a battle simulator. This is a test version so this isn’t legitimate. Right now, I have 3 files. functions.py, main.py, and charSelect.py. Currently, functions.py has all of the smaller functions, the variables and most imports. main.py and charSelect.py both import all from functions.py. main.py imports the function inside of charSelect.py and there’s my issue. After printing the variables, the variables are their base value from functions.py. I am unable to figure out why this is that.
charSelect.py
from functions import *
main.py
from functions import *
from charSelect import charSelection
while True:
charSelection()
print(f”””
A bunch of variables“””)
After using the charSelection function in the file main.py 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 charSelect.py file, you are in the main.py import new variable values.
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 functions.py 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.
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.
When you use from functions import *, you are importing variables into the namespace of the importing module (main.py and charSelect.py), 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 charSelect.py modifies any of the imported variables, these changes will only be reflected within charSelect.py’s namespace. main.py will still have the original values that were imported when it first ran from functions import *.
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.)
Put your entire game into a class, and turn module variables into instance attributes.
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.