python – Importing variables from another file?
python – Importing variables from another file?
from file1 import *
will import all objects and methods in file1
Import file1
inside file2
:
To import all variables from file1 without flooding file2s namespace, use:
import file1
#now use file1.x1, file2.x2, ... to access those variables
To import all variables from file1 to file2s 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.
python – Importing variables from another file?
Best to import x1 and x2 explicitly:
from file1 import x1, x2
This allows you to avoid unnecessary namespace conflicts with variables and functions from file1
while working in file2
.
But if you really want, you can import all the variables:
from file1 import *