Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception similar to ModuleNotFoundError in Python 2.7?

I'm trying to add some explicit exceptions to a piece of code, but the problem is that I have Python 3 and it has to be Python 2.7 compatible with the ModuleNotFoundError in Python 3. So any which exception is similar to that in Python 2.7?

like image 356
Moltres Avatar asked Sep 30 '18 16:09

Moltres


People also ask

Why am I getting an import error in Python?

Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .

What is module not found error in Python?

As the name implies, this error occurs when you're trying to access or use a module that cannot be found. In the case of the title, the "module named Python" cannot be found. Here are a few reasons why a module may not be found: you do not have the module you tried importing installed on your computer.

What error is caused by importing an unknown module?

The ImportError is raised when an import statement has trouble successfully importing the specified module. Typically, such a problem is due to an invalid or incorrect path, which will raise a ModuleNotFoundError in Python 3.6 and newer versions.


1 Answers

Use ImportError. ModuleNotFoundError is a subclass of ImportError, and a very new one, having only been introduced in Python 3.6.

If you want to use ModuleNotFoundError when it's available and ImportError if it's not, you can make a feature check:

try:
    ModuleNotFoundError
except NameError:
    ModuleNotFoundError = ImportError

# later
raise ModuleNotFoundError(whatever_message)
like image 181
user2357112 supports Monica Avatar answered Oct 19 '22 19:10

user2357112 supports Monica