Skip to content

Commit

Permalink
Avoid repeated initialization of the shim module
Browse files Browse the repository at this point in the history
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ó <[email protected]>
  • Loading branch information
nforro committed Feb 10, 2023
1 parent ab78f14 commit f0978c7
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions rpm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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.
"""
Expand All @@ -81,11 +85,20 @@ 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
else:
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

0 comments on commit f0978c7

Please sign in to comment.