Modernise importlib usage

`find_module` is deprecated in all supported version of Python and
is slated for removal in the upcoming 3.12. Happily it seems we
can move to the related `find_spec` and just hoist the loader from
the spec which that returns. (This is mostly what current `find_module`
implementations do anyway).
This commit is contained in:
Peter Law
2023-05-27 13:59:48 +01:00
parent d67facc922
commit c137eb6918
2 changed files with 10 additions and 12 deletions

View File

@@ -21,11 +21,11 @@ class _ExactImporter(MetaPathFinder):
def __init__(self, path_dct): def __init__(self, path_dct):
self._path_dct = path_dct self._path_dct = path_dct
def find_module(self, fullname, path=None): def find_spec(self, fullname, path=None, target=None):
if path is None and fullname in self._path_dct: if path is None and fullname in self._path_dct:
p = self._path_dct[fullname] p = self._path_dct[fullname]
loader = PathFinder.find_module(fullname, path=[p]) spec = PathFinder.find_spec(fullname, path=[p], target=target)
return loader return spec
return None return None

View File

@@ -2,7 +2,6 @@ import sys
import os import os
import inspect import inspect
import importlib import importlib
import warnings
from pathlib import Path from pathlib import Path
from zipfile import ZipFile from zipfile import ZipFile
from zipimport import zipimporter, ZipImportError from zipimport import zipimporter, ZipImportError
@@ -167,17 +166,16 @@ def _find_module(string, path=None, full_name=None, is_global_search=True):
def _find_module_py33(string, path=None, loader=None, full_name=None, is_global_search=True): def _find_module_py33(string, path=None, loader=None, full_name=None, is_global_search=True):
loader = loader or importlib.machinery.PathFinder.find_module(string, path) if not loader:
spec = importlib.machinery.PathFinder.find_spec(string, path)
if spec is not None:
loader = spec.loader
if loader is None and path is None: # Fallback to find builtins if loader is None and path is None: # Fallback to find builtins
try: try:
with warnings.catch_warnings(record=True): spec = importlib.util.find_spec(string)
# Mute "DeprecationWarning: Use importlib.util.find_spec() if spec is not None:
# instead." While we should replace that in the future, it's loader = spec.loader
# probably good to wait until we deprecate Python 3.3, since
# it was added in Python 3.4 and find_loader hasn't been
# removed in 3.6.
loader = importlib.find_loader(string)
except ValueError as e: except ValueError as e:
# See #491. Importlib might raise a ValueError, to avoid this, we # See #491. Importlib might raise a ValueError, to avoid this, we
# just raise an ImportError to fix the issue. # just raise an ImportError to fix the issue.