Skip to content

Commit

Permalink
Merge pull request #10819 from jan-cerny/python_imp
Browse files Browse the repository at this point in the history
Stop using "imp" module
  • Loading branch information
Mab879 authored Jul 12, 2023
2 parents 52bf2bb + 9fd541b commit ccd4ca5
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions ssg/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from __future__ import print_function

import os
import imp
import glob

from collections import namedtuple
Expand Down Expand Up @@ -38,6 +37,24 @@
TEMPLATE_YAML_FILE_NAME = "template.yml"


def load_module(module_name, module_path):
try:
# Python 2.7
from imp import load_source
return load_source(module_name, module_path)
except ImportError:
# https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
import importlib
spec = importlib.util.spec_from_file_location(module_name, module_path)
if not spec:
raise ValueError("Error loading '%s' module" % module_path)
module = importlib.util.module_from_spec(spec)
if not spec.loader:
raise ValueError("Error loading '%s' module" % module_path)
spec.loader.exec_module(module)
return module


class Template:
def __init__(self, templates_root_directory, name):
self.langs = []
Expand Down Expand Up @@ -83,8 +100,8 @@ def preprocess(self, parameters, lang):
def _preprocess_with_template_module(self, parameters, lang):
if self.preprocessing_file_path is not None:
unique_dummy_module_name = "template_" + self.name
preprocess_mod = imp.load_source(unique_dummy_module_name,
self.preprocessing_file_path)
preprocess_mod = load_module(
unique_dummy_module_name, self.preprocessing_file_path)
if not hasattr(preprocess_mod, "preprocess"):
msg = (
"The '{name}' template's preprocessing file {preprocessing_file} "
Expand Down

0 comments on commit ccd4ca5

Please sign in to comment.