Skip to content

Commit

Permalink
Use importlib instead of deprecated imp, if possible
Browse files Browse the repository at this point in the history
Also, imp has been removed in Python 3.12
  • Loading branch information
frenzymadness authored and zmiklank committed Jul 20, 2023
1 parent 04b6cc7 commit b6756e3
Showing 1 changed file with 31 additions and 2 deletions.
33 changes: 31 additions & 2 deletions distgen/generator.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import os
import sys
import imp
import jinja2
import functools

Expand All @@ -11,6 +10,14 @@
from distgen.commands import Commands
from distgen.multispec import Multispec, MultispecError

try:
from importlib.machinery import SourceFileLoader, SourcelessFileLoader
from importlib.util import spec_from_loader, module_from_spec
USE_IMP = False
except ImportError:
import imp
USE_IMP = True


class Generator(object):
project = None
Expand Down Expand Up @@ -81,16 +88,38 @@ def string_load(name):
self.project.abstract_initialize()

@staticmethod
def _load_python_file(filename):
def _load_python_file_importlib(filename):
""" load compiled python source """
mod_name, file_ext = os.path.splitext(os.path.split(filename)[-1])
if file_ext.lower() == '.py':
Loader = SourceFileLoader
elif file_ext.lower() == '.pyc':
Loader = SourcelessFileLoader

loader = Loader(mod_name, filename)
spec = spec_from_loader(loader.name, loader)
py_mod = module_from_spec(spec)
loader.exec_module(py_mod)

return py_mod

@staticmethod
def _load_python_file_imp(filename):
""" load compiled python source """
mod_name, file_ext = os.path.splitext(os.path.split(filename)[-1])
if file_ext.lower() == '.py':
# pylint: disable=used-before-assignment
py_mod = imp.load_source(mod_name, filename)
elif file_ext.lower() == '.pyc':
py_mod = imp.load_compiled(mod_name, filename)

return py_mod

if USE_IMP:
_load_python_file = _load_python_file_imp
else:
_load_python_file = _load_python_file_importlib

def _load_obj_from_file(self, filename, objname):
py_mod = self._load_python_file(filename)

Expand Down

0 comments on commit b6756e3

Please sign in to comment.