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')
#}
1
  • 1
    "call a module on different file"? This might help. As a side note, I'm really not keen on the commented-out braces Commented Sep 8, 2018 at 18:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.