Pqp239
Pqp239

Reputation: 35

Python module check if

So, I am working on a project for a class I'm in. So far I have two files. Spark.py and main.py. In my main file I have:

import os
import csv

from Spark import *

Spark.py requires the os module to be imported however it was already imported in main.py so I don't want to import it again. But I want Spark to check if main.py imported os so if it didn't spark.py would import it.

I tried to find if os was imported by checking if it was in globals().keys() but when I tried I realized that it wasn't there since it wasn't imported in Spark.py I looked around and couldn't find what I was looking for (mainly because I wasn't sure what to search for).

Is there a way for Spark.py or an imported module to to check if another module was imported with it? Such as Spark.py checking if main.py the file that imported it imported os.

Upvotes: 1

Views: 129

Answers (2)

hivert
hivert

Reputation: 10657

I don't think it's worth doing that. To check that a module is already imported you hav to look for it in sys.modules. However it seems that its faster than reimporting it:

 >>> %timeit import os
 1000000 loops, best of 3: 446 ns per loop
 >>> %timeit if 'os' in sys.modules: import os
 1000000 loops, best of 3: 547 ns per loop

So don't bother ! Just import.

Upvotes: 0

zhangxaochen
zhangxaochen

Reputation: 33997

All your imported modules are cached in sys.modules:

In [1483]: 'os' in sys.modules
Out[1483]: True

so import os within 2 files wouldn't import the os module twice.

Note that it's the module itself been cached, not the alias:

In [1484]: import os as oops

In [1485]: 'oops' in sys.modules
Out[1485]: False

Upvotes: 1

Related Questions