diff options
author | Chris Dent <cdent@anticdent.org> | 2023-04-30 10:50:23 +0100 |
---|---|---|
committer | Chris Dent <chris.dent@gmail.com> | 2023-04-30 12:27:06 +0100 |
commit | 7f60a6dfb501782d219bc0bb028728a5b4ef438a (patch) | |
tree | 7d1f666967471fb2e040a4a3b95ca83243c199b2 | |
parent | 36fd9632d6ad880b24177a08435eb8e1f9b01714 (diff) | |
download | paste-git-cdent/use-importlib.tar.gz |
Augment use of imp with importlib.utilcdent/use-importlib
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
-rw-r--r-- | paste/urlparser.py | 35 |
1 files 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): |