Skip to content

Commit f91af3a

Browse files
committed
Update TornadoImport for newer Python versions
Starting with Python 3.12, the import machinery does not use find_module() anymore [0]. To intercept the import, we only need to override find_spec() method in a finder. -- [0]: python/cpython#98040
1 parent 79009d5 commit f91af3a

1 file changed

Lines changed: 14 additions & 21 deletions

File tree

‎salt/__init__.py‎

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44

55
import importlib
6+
import importlib.util
67
import sys
78
import warnings
89

@@ -16,33 +17,25 @@
1617

1718

1819
class TornadoImporter:
19-
def find_module(self, module_name, package_path=None):
20-
if USE_VENDORED_TORNADO:
21-
if module_name.startswith("tornado"):
22-
return self
23-
else:
24-
if module_name.startswith("salt.ext.tornado"):
25-
return self
26-
return None
27-
28-
def load_module(self, name):
29-
if USE_VENDORED_TORNADO:
30-
mod = importlib.import_module("salt.ext.{}".format(name))
31-
else:
32-
# Remove 'salt.ext.' from the module
33-
mod = importlib.import_module(name[9:])
34-
sys.modules[name] = mod
35-
return mod
20+
"""Implementation of importlib.abc.MetaPathFinder that intercepts tornado imports.
3621
37-
def create_module(self, spec):
38-
return self.load_module(spec.name)
22+
Normally, a Finder is only responsible for finding a source. However, we not
23+
only need to redirect the import, we also need to add it to sys.modules.
24+
That's outside of a finder's scope, but it is easiest to do it in one place.
25+
"""
3926

40-
def exec_module(self, module):
27+
def find_spec(self, fullname, path=None, target=None):
28+
if USE_VENDORED_TORNADO and fullname.startswith("tornado"):
29+
vendored_name = fullname.replace("tornado", "salt.ext.tornado", 1)
30+
spec = importlib.util.find_spec(vendored_name)
31+
if spec is not None:
32+
sys.modules[fullname] = importlib.import_module(vendored_name)
33+
return spec
4134
return None
4235

4336

4437
# Try our importer first
45-
sys.meta_path = [TornadoImporter()] + sys.meta_path
38+
sys.meta_path.insert(0, TornadoImporter())
4639

4740

4841
# All salt related deprecation warnings should be shown once each!

0 commit comments

Comments
 (0)