Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing the same modules in different files

Tags:

python

import

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 ?

like image 203
Utsav T Avatar asked Jun 19 '15 18:06

Utsav T


People also ask

What happens if I import the same module twice Python?

The answer Also, when importing modules from the same path, the same module instance is returned.

How can I import modules if file is not in same directory?

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.

Can modules import each other?

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.

How do I import an entire module?

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.


1 Answers

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.

like image 134
Zack Tanner Avatar answered Oct 27 '22 00:10

Zack Tanner