1

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?

2
  • 3
    from my_file import my_variable? Commented Sep 2, 2014 at 12:00
  • 1
    yes. for example if a variable x in a file say test.py, you can import it in another file like import test, test.x Commented Sep 2, 2014 at 12:03

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.