views:

55

answers:

2

In Python, import does_not_exist raises ImportError, and

import exists

exists.py:

import does_not_exist

will also raise ImportError.

How should I tell the difference in code?

+3  A: 

The only method I know is to check if the toplevel modulename "exists" is in the Exception's message or not:

try:
  import exists
except ImportError as exc:
  if "exists" in str(exc):
     pass
  else:
     raise

Could this be a feature request for Python's ImportError? Having a variable for the module name would certainly be convenient..

kaizer.se
+2  A: 

You can use the tb_next of the traceback. It will be different from None if the exception occured on another module

import sys
try:
    import exists
except Exception, e:
    print "None on exists", sys.exc_info()[2].tb_next == None

try:
    import notexists
except Exception, e:
    print "None on notexists", sys.exc_info()[2].tb_next == None

>>> None on exists False
>>> None on notexists True
luc
Good idea. Unfortunately it breaks when you're running under `rpdb2`'s import hook.
joeforker