2

I was wondering what happens if I call a module on different file, which imports the same python module that is already imported on the main call, is it imported twice? If yes, how can I prevent it? What is recommended way for this?

On the following example time module is imported on the both files. As alternative solution, I passed time module as an argument to the module call that is located on different file.


Example:

hello.py

from module import module
import time

time.sleep(1)
module();

module.py

import time; # Already imported in hello.py

def module(): #{
    time.sleep(1)
    print('hello')  
#}

Alternative: I am passing time module as argument into module() function that is located under module.py.

hello.py

from module import module
import time

time.sleep(1)
module(time);

module.py

def module(time): #{ 
    time.sleep(1)
    print('hello')
#}
alper
  • 2,919
  • 9
  • 53
  • 102
  • 1
    "call a module on different file"? [This](https://stackoverflow.com/questions/296036/does-python-optimize-modules-when-they-are-imported-multiple-times) might help. As a side note, I'm really not keen on the commented-out braces – roganjosh Sep 08 '18 at 18:22

1 Answers1

4

A module is only located and executed once, no matter how many times it is imported. It's stored in the sys.modules dict, so subsequent imports are just a dictionary lookup. There's no reason to try to avoid multiple imports of the same module.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662