In Python, when an import fails, how can I differentiate between:
- The module doesn't exist.
- The module exists, but it tried importing another module that didn't exist.
Example
# ./first.py
try:
import second
except ImportError:
print("second.py doesn't exist")
# ./second.py
import third # ModuleNotFoundError: No module named "third"
# Do stuff...
def foo():
...
>>> import first
second.py doesn't exist
The error message printed in this example is incorrect. second.py does exist, and the ImportError is actually due to second.py itself containing an invalid import.
In this case, I want all transitive errors in second.py to propagate un-caught. The only exception I want to catch is the case where there is no file second.py to import.
This paradigm has been discussed on Software Engineering SE but without a method for differentiation.
Yes, I am fully aware that this is a strange situation and probably smells like an xy-problem. This is all for some temporary testing, where second.py is a script I'm creating and deleting as I test things: not strictly necessary, but now I'm interested in the question theoretically.