7

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 ?

4
  • yes. you are using os independently in both modules. Jun 19, 2015 at 18:35
  • 1
    You can find this out yourself easily: Try running your program when you omit import os in one of the files.
    – mkrieger1
    Jun 19, 2015 at 18:36
  • By the way, instead of my_module.m = myclass(...), you should write m = my_module.myclass(...).
    – mkrieger1
    Jun 19, 2015 at 18:37
  • You would have to use my_module.os.. Jun 19, 2015 at 18:37

1 Answer 1

7

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.