From ba9714422feca1bfb3a964bc01f4c364683ca70c Mon Sep 17 00:00:00 2001 From: bijanagahi Date: Fri, 14 Mar 2025 15:24:04 -0600 Subject: [PATCH] Add importlib compatibility for newer versions of Python In newer versions of python the imp module has been removed and replaced with importlib. Without changing too much of base behavior, this change allows users with newer versions of python to continue using heroprotocol. --- heroprotocol/versions/__init__.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/heroprotocol/versions/__init__.py b/heroprotocol/versions/__init__.py index eeba98d..d4dac52 100644 --- a/heroprotocol/versions/__init__.py +++ b/heroprotocol/versions/__init__.py @@ -6,7 +6,6 @@ import os import re -import imp import sys @@ -16,6 +15,9 @@ def _import_protocol(base_path, protocol_module_name): This implementation is derived from the __import__ example here: https://docs.python.org/2/library/imp.html + + In Python3, imp has been succeeded by importlib, example here: + https://docs.python.org/3/library/importlib.html """ # Try to return the module if it's been loaded already @@ -25,9 +27,17 @@ def _import_protocol(base_path, protocol_module_name): # If any of the following calls raises an exception, # there's a problem we can't handle -- let the caller handle it. # - fp, pathname, description = imp.find_module(protocol_module_name, [base_path]) + fp = None try: - return imp.load_module(protocol_module_name, fp, pathname, description) + if sys.version_info[0] == 3: + import importlib + sys.path.append(base_path) + module = importlib.import_module(protocol_module_name) + return module + else: + import imp + fp, pathname, description = imp.find_module(protocol_module_name, [base_path]) + return imp.load_module(protocol_module_name, fp, pathname, description) finally: # Since we may exit via an exception, close fp explicitly. if fp: