Skip to content

Commit

Permalink
Avoid repeated initialization of the shim module (#3)
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.
  • Loading branch information
nforro authored Feb 13, 2023
2 parents ab78f14 + 36e8a42 commit 5317d3d
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 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,23 @@ 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}")
logger.debug(f"Exception: {type(e)}: {e}")
continue
else:
raise ImportError("Failed to import system RPM module")


init_module()
raise ImportError(
"Failed to import system RPM module. "
"Make sure RPM Python bindings are installed on your system."
)


# 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 5317d3d

Please sign in to comment.