Supposing I have written a set of classes to be used in a python file and use them in a script (or python code in a different file). Now both the files require a set of modules to be imported. Should the import be included only once, or in both the files ?
File 1 : my_module.py.
import os
class myclass(object):
def __init__(self,PATH):
self.list_of_directories = os.listdir(PATH)
File 2 :
import os
import my_module
my_module.m = myclass("C:\\User\\John\\Desktop")
list_ = m.list_of_directories
print os.getcwd()
Should I be adding the line import os
to both the files ?
How does this impact the performance, supposing there are lots of modules to be imported ? Also, is a module ,once imported, reloaded in this case ?
The answer Also, when importing modules from the same path, the same module instance is returned.
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names, if placed at the top level of a module (outside any functions or classes), are added to the module's global namespace.
You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.
Each file that you are using a module in, must import that module. Each module is its own namespace. Things you explicitly import within that file are available in that namespace. Thus, if you need os
in both files, you should import them in both files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With