Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python importing

Tags:

python

import

I have a file, myfile.py, which imports Class1 from file.py and file.py contains imports to different classes in file2.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?

like image 320
Boolean Avatar asked Jan 26 '26 20:01

Boolean


2 Answers

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!-).

like image 74
Alex Martelli Avatar answered Jan 29 '26 08:01

Alex Martelli


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.

like image 26
Mike Graham Avatar answered Jan 29 '26 09:01

Mike Graham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!