So I have two python files. Let's call them module.py and main.py. module.py looks like this:
name = "bob"
age = 20
def changename():
name = "tim"
and main.py looks like this:
import module
print(module.name)
module.changename()
print(module.name)
When I run main.py, I get this output, as expected:
>"bob"
>"tim"
However, always having to write module.name will get very time consuming, so I can do from module import *, which imports all of the variables and functions into main.py. However, after changing the code in main.py to this:
from module import *
print(name)
changename()
print(name)
I get this output:
>"bob"
>"bob"
I assume that this is because python imports the values of the variables at the beginning, and then doesn't update them when they get changed by functions within module.py.
My question is, is there a way to nicely import all the functions and variables from a module, but still allow the module to update it's variables?
Thanks in advance!
2 Answers 2
I think the best way is to write getter and setter functions in module.py for each global variable you want to share. Like this:
name = "bob"
age = 20
def changename():
global name # This tells that name is not local variable.
name = "tim"
def getname():
return name
Then, you can use these getters in main.py like this:
import module
print(module.getname())
module.changename()
print(module.getname())
But I recommend to import functions one by one to prevent long names. Like this:
from module import changename
from module import getname
print(getname())
changename()
print(getname())
I tested these codes with Python2.7. Define a variable as a global one, before setting a value to it; because setting a value to a variable in a function makes it local (my Python acts in this way!).
Comments
After some testing, I realise that the best way to do this would be to have a third file called 'variables.py' imported as something short, as @jonrsharpe suggested. Both files can change or view variables.name.
from module import *is generally bad practice; if you need a shorter name,import module as m.