From 7f60a6dfb501782d219bc0bb028728a5b4ef438a Mon Sep 17 00:00:00 2001 From: Chris Dent Date: Sun, 30 Apr 2023 10:50:23 +0100 Subject: Augment use of imp with importlib.util imp is deprecated and will go away in Python 3.12 (which is very soon). The preferred replacement is importlib. However, importlib is not available in Python 2.7, so we want to keep both in order to maintain 2.7 some semblance of 2.7 support. This implementation is based on the importlib docs [1] and passes the quite robust tests that are already present for the urlparser module. Unfortunately there's no good way to be 100% certain that this works for all the many ways that Paste can do an import. So this patch is mostly hoping that test coverage is sufficient. [1] https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly Fixes #75 --- paste/urlparser.py | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/paste/urlparser.py b/paste/urlparser.py index 19bcbac..d4a67ce 100644 --- a/paste/urlparser.py +++ b/paste/urlparser.py @@ -7,7 +7,12 @@ WSGI applications that parse the URL and dispatch to on-disk resources import os import six import sys -import imp + +if six.PY2: + import imp +else: + import importlib.util as imputil + import mimetypes try: import pkg_resources @@ -376,7 +381,6 @@ def load_module_from_name(environ, filename, module_name, errors): return None f.write('#\n') f.close() - fp = None if module_name in sys.modules: return sys.modules[module_name] if '.' in module_name: @@ -386,14 +390,25 @@ def load_module_from_name(environ, filename, module_name, errors): parent_name, errors) else: base_name = module_name - fp = None - try: - fp, pathname, stuff = imp.find_module( - base_name, [os.path.dirname(filename)]) - module = imp.load_module(module_name, fp, pathname, stuff) - finally: - if fp is not None: - fp.close() + module = None + + if six.PY2: + fp = None + try: + fp, pathname, stuff = imp.find_module( + base_name, [os.path.dirname(filename)]) + module = imp.load_module(module_name, fp, pathname, stuff) + finally: + if fp is not None: + fp.close() + else: + # imp is deprecated and will be removed in Python 3.12 + spec = imputil.spec_from_file_location(base_name, filename) + if spec is not None: + module = imputil.module_from_spec(spec) + sys.modules[base_name] = module + spec.loader.exec_module(module) + return module def make_py(parser, environ, filename): -- cgit v1.2.1