Python Glossary Русский

all Python 3Exceptionsexception

ImportError

built-in exceptions

Raised when an import fails: the module cannot be found (ModuleNotFoundError) or a from … import names something the module lacks.

Syntax

raise ImportError('сообщение')

The usual confusion is with ModuleNotFoundError: it is a subclass of ImportError, so except ImportError catches both "no such module" and "module exists, but the requested name is not in it". That is the trap — wrapping an optional dependency in try/except ImportError also silently swallows a real failure inside that module, namely its own broken import. An error in the module body itself (a typo gives NameError) propagates unchanged, and except ImportError does not catch it. The caught object carries name and path attributes telling you which module and file actually failed.

Examples

from os import nonexistent  # ImportError
try:
    import some_module
except ImportError:
    print('модуль недоступен')

See also

Open in the full glossarydocs.python.orgReport an inaccuracy