From f0978c700ee488b5aaa65dd5df7f2ac2f9e95898 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Forr=C3=B3?= Date: Fri, 10 Feb 2023 20:57:47 +0100 Subject: [PATCH] Avoid repeated initialization of the shim module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the shim module tries to reload itself, it repeats the loop of trying all the sitepackages directories, and because importlib.reload() is noop when called recursively, it ends up raising ImportError that is visible to the user. Even though execution returns to the original loop and the system RPM module is loaded successfully, the error message produced is very confusing. Improve that by avoiding repeated initialization of the shim module. Also make sure that importlib.reload(), when loading the shim module for the second time, throws a specific exception that doesn't trigger any log message, to make things even less confusing. Signed-off-by: Nikola Forró --- rpm/__init__.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/rpm/__init__.py b/rpm/__init__.py index d9e5582..967a66f 100644 --- a/rpm/__init__.py +++ b/rpm/__init__.py @@ -20,6 +20,10 @@ logger = logging.getLogger(PROJECT_NAME) +class ShimAlreadyInitializingError(Exception): + pass + + def get_system_sitepackages() -> List[str]: """ Gets a list of sitepackages directories of system Python interpreter(s). @@ -71,7 +75,7 @@ def try_path(path: str) -> bool: return False -def init_module() -> None: +def initialize() -> None: """ Initializes the shim. Tries to load system RPM module and replace itself with it. """ @@ -81,6 +85,8 @@ def init_module() -> None: if try_path(path): logger.debug("Import successfull") return + except ShimAlreadyInitializingError: + continue except Exception as e: logger.error(f"Exception: {e}") continue @@ -88,4 +94,11 @@ def init_module() -> None: raise ImportError("Failed to import system RPM module") -init_module() +# avoid repeated initialization of the shim module +try: + _shim_module_initializing_ +except NameError: + _shim_module_initializing_: bool = True + initialize() +else: + raise ShimAlreadyInitializingError