Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if python module exists and can be imported [duplicate]

I am using debug toolbar with django and would like to add it to project if two conditions are true:

  • settings.DEBUG is True
  • module itself exists

It's not hard to do the first one

# adding django debug toolbar if DEBUG:     MIDDLEWARE_CLASSES += 'debug_toolbar.middleware.DebugToolbarMiddleware',     INSTALLED_APPS += 'debug_toolbar', 

But how do I check if module exists?

I have found this solution:

try:     import debug_toolbar except ImportError:     pass 

But since import happens somewhere else in django, I need if/else logic to check if module exists, so I can check it in settings.py

def module_exists(module_name):     # ??????  # adding django debug toolbar if DEBUG and module_exists('debug_toolbar'):     MIDDLEWARE_CLASSES += 'debug_toolbar.middleware.DebugToolbarMiddleware',     INSTALLED_APPS += 'debug_toolbar', 

Is there a way to do it?

like image 341
Silver Light Avatar asked May 01 '11 10:05

Silver Light


People also ask

How do I check if a Python module exists?

To check all the installed Python modules, we can use the following two commands with the 'pip': Using 'pip freeze' command. Using 'pip list command.

Can we import same package twice in Python?

Ans. One can import the same package or same class multiple times.

Can we import a module twice?

The rules are quite simple: the same module is evaluated only once, in other words, the module-level scope is executed just once. If the module, once evaluated, is imported again, it's second evaluation is skipped and the resolved already exports are used.

How do you check if a module is already imported?

Use: if "sys" not in dir(): print("sys not imported!")


1 Answers

You can use the same logic inside your function:

def module_exists(module_name):     try:         __import__(module_name)     except ImportError:         return False     else:         return True 

There is no performance penalty to this solution because modules are imported only once.

like image 128
Sven Marnach Avatar answered Sep 23 '22 16:09

Sven Marnach