From e86d717035af317dab5d62851181873ec3c38ebe Mon Sep 17 00:00:00 2001 From: Remco Burema Date: Fri, 20 Oct 2023 14:40:10 +0200 Subject: [PATCH] Replace deprecated imp module with importlib. done as part of Python 3.12 spike (CURA-11078) --- UM/PluginRegistry.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/UM/PluginRegistry.py b/UM/PluginRegistry.py index 25ef35e56..53dc882b9 100644 --- a/UM/PluginRegistry.py +++ b/UM/PluginRegistry.py @@ -1,11 +1,13 @@ -# Copyright (c) 2022 Ultimaker B.V. +# Copyright (c) 2023 UltiMaker # Uranium is released under the terms of the LGPLv3 or higher. -import imp +import importlib.util +import importlib.machinery import json import os import shutil # For deleting plugin directories; import stat # For setting file permissions correctly; +import sys import time import types import zipfile @@ -762,7 +764,10 @@ def _findPlugin(self, plugin_id: str) -> Optional[types.ModuleType]: except Exception: pass try: - file, path, desc = imp.find_module(plugin_id, [final_location]) + spec = importlib.machinery.PathFinder().find_spec(plugin_id, [final_location]) + if len(spec.submodule_search_locations) != 1: + raise IndexError(f"Attempt to load plugin '{plugin_id}' from {len(spec.submodule_search_locations)} locations.") + path = spec.submodule_search_locations[0] except Exception: Logger.logException("e", "Import error when importing %s", plugin_id) return None @@ -783,13 +788,12 @@ def _findPlugin(self, plugin_id: str) -> Optional[types.ModuleType]: return None try: - module = imp.load_module(plugin_id, file, path, desc) # type: ignore #MyPy gets the wrong output type from imp.find_module for some reason. + module = importlib.util.module_from_spec(spec) + sys.modules[plugin_id] = module + spec.loader.exec_module(module) except Exception: Logger.logException("e", "Import error loading module %s", plugin_id) return None - finally: - if file: - os.close(file) #type: ignore #MyPy gets the wrong output type from imp.find_module for some reason. self._found_plugins[plugin_id] = module return module