Importing variables from another file?


How can I import variables from one file to another?

example: file1 has the variables x1 and x2 how to pass them to file2?

How can I import all of the variables from one to another?

This question is tagged with python file variables import

~ Asked on 2013-06-22 22:04:40

The Best Answer is


from file1 import *  

will import all objects and methods in file1

~ Answered on 2013-06-22 22:09:52


Import file1 inside file2:

To import all variables from file1 without flooding file2's namespace, use:

import file1

#now use file1.x1, file2.x2, ... to access those variables

To import all variables from file1 to file2's namespace( not recommended):

from file1 import *
#now use x1, x2..

From the docs:

While it is valid to use from module import * at module level it is usually a bad idea. For one, this loses an important property Python otherwise has — you can know where each toplevel name is defined by a simple “search” function in your favourite editor. You also open yourself to trouble in the future, if some module grows additional functions or classes.

~ Answered on 2013-06-22 22:06:06

Most Viewed Questions: