Skip to content

Commit

Permalink
Augment use of imp with importlib.util (#76)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
cdent authored Apr 30, 2023
1 parent 36fd963 commit 0af287f
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions paste/urlparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@
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
Expand Down Expand Up @@ -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:
Expand All @@ -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):
Expand Down

0 comments on commit 0af287f

Please sign in to comment.