Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d71d426

Browse files
committed
ShimImporter: implement modern interface
1 parent 579c9f2 commit d71d426

2 files changed

Lines changed: 15 additions & 24 deletions

File tree

IPython/utils/shimmodule.py

Lines changed: 11 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
# Copyright (c) IPython Development Team.
44
# Distributed under the terms of the Modified BSD License.
55

6+
import importlib.abc
7+
import importlib.util
68
import sys
79
import types
810
from importlib import import_module
@@ -13,41 +15,26 @@
1315
class ShimWarning(Warning):
1416
"""A warning to show when a module has moved, and a shim is in its place."""
1517

16-
class ShimImporter(object):
18+
19+
class ShimImporter(importlib.abc.MetaPathFinder):
1720
"""Import hook for a shim.
18-
21+
1922
This ensures that submodule imports return the real target module,
2023
not a clone that will confuse `is` and `isinstance` checks.
2124
"""
2225
def __init__(self, src, mirror):
2326
self.src = src
2427
self.mirror = mirror
25-
28+
2629
def _mirror_name(self, fullname):
2730
"""get the name of the mirrored module"""
28-
29-
return self.mirror + fullname[len(self.src):]
3031

31-
def find_module(self, fullname, path=None):
32-
"""Return self if we should be used to import the module."""
33-
if fullname.startswith(self.src + '.'):
34-
mirror_name = self._mirror_name(fullname)
35-
try:
36-
mod = import_item(mirror_name)
37-
except ImportError:
38-
return
39-
else:
40-
if not isinstance(mod, types.ModuleType):
41-
# not a module
42-
return None
43-
return self
32+
return self.mirror + fullname[len(self.src) :]
4433

45-
def load_module(self, fullname):
46-
"""Import the mirrored module, and insert it into sys.modules"""
47-
mirror_name = self._mirror_name(fullname)
48-
mod = import_item(mirror_name)
49-
sys.modules[fullname] = mod
50-
return mod
34+
def find_spec(self, fullname, path, target=None):
35+
if fullname.startswith(self.src + "."):
36+
mirror_name = self._mirror_name(fullname)
37+
return importlib.util.find_spec(mirror_name)
5138

5239

5340
class ShimModule(types.ModuleType):

IPython/utils/tests/test_shimmodule.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,7 @@ def test_shim_warning():
88
sys.modules.pop('IPython.config', None)
99
with pytest.warns(ShimWarning):
1010
import IPython.config
11+
12+
import traitlets.config
13+
14+
assert IPython.config.Config is traitlets.config.Config

0 commit comments

Comments
 (0)