Python importing
Solution 1
Best practice is to import every module that defines identifiers you need, and use those identifiers as qualified by the module's name; I recommend using from
only when what you're importing is a module from within a package. The question has often been discussed on SO.
Importing a module, say moda
, from many modules (say modb
, modc
, modd
, ...) that need one or more of the identifiers moda
defines, does not slow you down: moda
's bytecode is loaded (and possibly build from its sources, if needed) only once, the first time moda
is imported anywhere, then all other imports of the module use a fast path involving a cache (a dict mapping module names to module objects that is accessible as sys.modules
in case of need... if you first import sys
, of course!-).
Solution 2
Python doesn't automatically introduce anything into the namespace of myfile.py, but you can access everything that is in the namespaces of all the other modules.
That is to say, if in file1.py you did from file2 import SomeClass
and in myfile.py you did import file1
, then you can access it within myfile as file1.SomeClass
. If in file1.py you did import file2
and in myfile.py you did import file1
, then you can access the class from within myfile as file1.file2.SomeClass
. (These aren't generally the best ways to do it, especially not the second example.)
This is easily tested.
Comments
-
Boolean almost 2 years
I have a file,
myfile.py
, which importsClass1
fromfile.py
andfile.py
contains imports to different classes infile2.py
,file3.py
,file4.py
.In my
myfile.py
, can I access these classes or do I need to again import file2.py, file3.py, etc.?Does Python automatically add all the imports included in the file I imported, and can I use them automatically?
-
Mike Graham about 14 yearsWhat motivated you to ask this question?
-
Boolean about 14 yearsI have this opensource code, I downloaded. They are doing something like this. I worked with java and I know that this is not possible in java. So confused and asked.
-
-
Ignacio Vazquez-Abrams about 14 yearsBut please, please, please don't do this. Explicitly import all modules your code will need.
-
Mike Graham about 14 yearsYes and no. Depending on how file1.py is supposed to work, it might be the right place from which to access
SomeClass
. (The latter example is always bad form.)