I want to use a variable that I assigned in another file, is there a way that the import of that variable from that file will maintain the value of the variable?
asked Sep 2, 2014 at 11:59
snufsan
2131 gold badge3 silver badges7 bronze badges
2 Answers 2
If you define a variable my_variable in a module called my_module.py and it has been initialized, you can access to it from another module:
from my_module import my_variable
You can also do:
import my_module
...
my_module.my_variable
but I recommend the first option if you only need that variable from my_module.py
answered Sep 2, 2014 at 12:03
juankysmith
12.5k6 gold badges40 silver badges65 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
If a file ham.py contains:
eggs = 1
Then in spam.py you can say:
from ham import eggs
print eggs
Or:
import ham
print ham.eggs
answered Sep 2, 2014 at 12:05
lynn
10.9k1 gold badge48 silver badges81 bronze badges
Comments
lang-py
from my_file import my_variable?xin a file saytest.py, you can import it in another file likeimport test,test.x