howto check does module 'asdf' exist? (is available for import)

D

dmitrey

howto check does module 'asdf' exist (is available for import) or no?
(without try/cache of course)
Thx in advance, D.
 
S

Stefan Behnel

dmitrey said:
howto check does module 'asdf' exist (is available for import) or no?

Walk through sys.path and find it yourself?

(without try/cache of course)

Why is the obvious (and most common) try/import/catch solution "of course" out?

Stefan
 
A

Asun Friere

howto check does module 'asdf' exist (is available for import) or no?

try :
import asdf
del asdf
except ImportError :
#do stuff ...
(without try/cache of course)

Oops sorry, you didn't want it the obvious way ... but why ever not?
 
A

Asun Friere

howto check does module 'asdf' exist (is available for import) or no?
try :
import asdf
del asdf
except ImportError :
print "module asdf not available"
else :
print "module asdf available for loading"

You can generalise this, but at the expense of a couple of exec
statements:
def is_module_available (module) :
try :
exec('import %s' % module)
exec('del %s' % module)
except ImportError :
return False
else :
return True
(without try/cache of course)
Oops sorry, you wanted it done in some non-obvious way! Why?!
 
C

Carsten Haese

You can generalise this, but at the expense of a couple of exec
statements:
def is_module_available (module) :
try :
exec('import %s' % module)
exec('del %s' % module)
except ImportError :
return False
else :
return True

You can save the exec statement by using the built-in __import__
function:

def is_module_available(modulename):
try: mod = __import__(modulename)
except ImportError: return False
else: return True
 
P

Paul Rubin

Asun Friere said:
try :
import asdf
del asdf
except ImportError :
print "module asdf not available"
else :
print "module asdf available for loading"

But this has a side effect: if asdf is already loaded, it deletes it.
 
K

kaens

I think that's there because you just wanted to check if it was
available for import, implying that you didn't actually want to import
it right then.
 
P

Paul Rubin

kaens said:
I think that's there because you just wanted to check if it was
available for import, implying that you didn't actually want to import
it right then.

Whether it's available for import and whether you've already imported
it are two separate questions. Maybe you said "import fghj as asdf"
and now you want to find out if there's another module actually named
asdf. It would be cleaner if there's a method with no side effects.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top