From c2ae085713ac810a3dc72807f5c61b60b0d496d8 2021-11-17 03:51:54 From: Nikita Kniazev Date: 2021-11-17 03:51:54 Subject: [PATCH] ImportDenier: implement modern interface --- diff --git a/IPython/external/qt_loaders.py b/IPython/external/qt_loaders.py index 982590e..3351e88 100644 --- a/IPython/external/qt_loaders.py +++ b/IPython/external/qt_loaders.py @@ -8,6 +8,7 @@ bindings, which is unstable and likely to crash This is used primarily by qt and qt_for_kernel, and shouldn't be accessed directly from the outside """ +import importlib.abc import sys import types from functools import partial, lru_cache @@ -47,7 +48,7 @@ api_to_module = { } -class ImportDenier(object): +class ImportDenier(importlib.abc.MetaPathFinder): """Import Hook that will guard against bad Qt imports once IPython commits to a specific binding """ @@ -59,14 +60,12 @@ class ImportDenier(object): sys.modules.pop(module_name, None) self.__forbidden.add(module_name) - def find_module(self, fullname, path=None): + def find_spec(self, fullname, path, target=None): if path: return if fullname in self.__forbidden: - return self - - def load_module(self, fullname): - raise ImportError(""" + raise ImportError( + """ Importing %s disabled by IPython, which has already imported an Incompatible QT Binding: %s """ % (fullname, loaded_api())) diff --git a/IPython/external/tests/__init__.py b/IPython/external/tests/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/IPython/external/tests/__init__.py diff --git a/IPython/external/tests/test_qt_loaders.py b/IPython/external/tests/test_qt_loaders.py new file mode 100644 index 0000000..7bc9ccf --- /dev/null +++ b/IPython/external/tests/test_qt_loaders.py @@ -0,0 +1,11 @@ +import importlib +import pytest +from IPython.external.qt_loaders import ID + + +def test_import_denier(): + ID.forbid("ipython_denied_module") + with pytest.raises(ImportError, match="disabled by IPython"): + import ipython_denied_module + with pytest.raises(ImportError, match="disabled by IPython"): + importlib.import_module("ipython_denied_module")