45

How to test if a module has been imported in python?

for example I need the basics:

if not has_imported("sys"):
   import sys

also

if not has_imported("sys.path"): 
   from sys import path

Thanks!

Rgs.

Thanks for all of your comments: the code been pasted here. auto import all sub modules in a folder then invoke same name functions - python runtime inspect related

Community
  • 1
  • 1
user478514
  • 3,859
  • 10
  • 33
  • 42
  • 5
    I can not imagine any case where you would have to worry about the performance of doing reloads on modules. Firstly because they are slow no matter what you do, secondly because if you need to reload a module so often that it has a performance issue you are doing things VERY WRONGLY. I bet a fiver on that you are barking up the wrong tree, and that you are trying to solve an issue in the entirely wrong way. Please always explain *why* you feel the need to solve the problem you want solved. It helps you get answers that put you on the right track. – Lennart Regebro Feb 17 '11 at 10:52
  • thanks, the code been pasted here: http://stackoverflow.com/questions/5037468/auto-import-all-sub-modules-in-a-folder-then-invoke-same-name-functions-python – user478514 Feb 18 '11 at 04:02

3 Answers3

51

If you want to optimize by not importing things twice, save yourself the hassle because Python already takes care of this.

If you need this to avoid NameErrors or something: Fix your sloppy coding - make sure you don't need this, i.e. define (import) everything before you ever use it (in the case if imports: once, at startup, at module level).

In case you do have a good reason: sys.modules is a dictionary containing all modules already imported somewhere. But it only contains modules, and because of the way from <module> import <variable> works (import the whole module as usual, extract the things you import from it), from sys import path would only add sys to sys.modules (if it wasn't already imported on startup). from pkg import module adds pkg.module as you probably expect.

Smi
  • 13,850
  • 9
  • 56
  • 64
  • thanks, so it means the optimize for the twice import is not necessary? how about the the 'reload(sys)' if i forgot the 'import sys', is that means i can 'import sys; reload(sys)' without lost performance? – user478514 Feb 17 '11 at 10:07
  • @user: `reload` explicitly circumvents the caching `import` uses to, well, reload a module if the source has changed since you imported it. You usually don't need it except when experimenting in the interactive prompt - and even there, late binding may come to the rescue (e.g. if you define `def f(): return os.listdir(os.getcwd())`, you can `import os` afterwards and future calls to the function will work!). –  Feb 17 '11 at 10:18
  • 1
    @user478514: "the optimize for the twice import is not necessary". Correct. Python already does this. Please read the tutorial again. The `import sys; reload(sys)` is a silly example. Since your code will will never do this, don't optimize for it. – S.Lott Feb 17 '11 at 10:56
  • 1
    Note that the sys.modules only contains the original name of the module, - not the aliased, e.g.: `import networkx as nx; import sys; 'nx' in sys.modules` returns `False`, while `import networkx as nx; import sys; 'networkx' in sys.modules` returns True. – Finn Årup Nielsen Sep 24 '14 at 10:17
15

I feel the answer that has been accepted is not fully correct.

Python still has overhead when importing the same module multiple times. Python handles it without giving you an error, sure, but that doesn't mean it won't slow down your script. As you will see from the URL below, there is significant overhead when importing a module multiple times.

For example, in a situation where you may not need a certain module except under a particular condition, if that module is large or has a high overhead then there is reason to import only on condition. That does not explicitly mean you are a sloppy coder either.

https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Import_Statement_Overhead

John
  • 976
  • 1
  • 15
  • 21
  • With CPython v3.5.1 it's an overhead of only ~3ns per call. Tested with `%timeit '''import json; json.dumps(data)'''` and `import json; %timeit '''json.dumps(data)'''` with `data = ['foo', {'bar': ('baz', None, 1.0, 2)}]`. – mab Jan 07 '16 at 14:17
  • 1
    Yeah, that makes sense. But the specific module you are loading can make a difference in that time too. Because when you import a module the code runs immediately - Keywords such as `def` and `class` are actively being loaded and run. That is why we have that `if __name__ == "__main__":` bit, so that code doesn't run unless you make a direct call to it. So to be honest here, I don't know for sure if subsequent calls to a module still run the code or not... – John Jul 28 '16 at 16:42
  • Good point, so the time for each import is dependent on the number of functions and (i.e. in case of seaborn) the possibility of code beeing executed during the sheer import. At least, it seems like CPython does not re-execute the code for subsequent import commands for the same module ([doc](https://docs.python.org/3/reference/import.html#the-module-cache)) - unless [importlib.reload(module)](https://docs.python.org/3/library/importlib.html#importlib.reload) is called manually. – mab Sep 09 '16 at 13:36
8
from sys import modules
try:
    module = modules[module_name]
except KeyError:
    __import__('m')   

this is my solution of changing code at runtime!

Jack Gao
  • 81
  • 1
  • 1