From 97982dd1385f065b04aa780c91aee9f67b9beda2 Mon Sep 17 00:00:00 2001 From: Mathias Guijarro Date: Thu, 24 Oct 2024 09:46:49 +0200 Subject: [PATCH] fix: ophyd patch, compatibility with Python >=3.12 "find_module" has been deleted from Finder class --- ophyd_devices/ophyd_patch.py | 43 ++++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/ophyd_devices/ophyd_patch.py b/ophyd_devices/ophyd_patch.py index 31526d3..783e0d1 100644 --- a/ophyd_devices/ophyd_patch.py +++ b/ophyd_devices/ophyd_patch.py @@ -2,6 +2,7 @@ import importlib import importlib.util import pathlib import sys +from importlib.abc import Loader, MetaPathFinder from types import ModuleType _patched_status_base = """ @@ -42,7 +43,24 @@ class StatusBase(_StatusBase): """ -class _CustomImporter: +class _CustomLoader(Loader): + def __init__(self, patched_code): + self.patched_code = patched_code + + def load_module(self, fullname): + """Load and execute ophyd.status""" + status_module = ModuleType("ophyd.status") + status_module.__loader__ = self + status_module.__file__ = None + status_module.__name__ = fullname + + exec(self.patched_code, status_module.__dict__) + sys.modules[fullname] = status_module + + return status_module, True + + +class _CustomImporter(MetaPathFinder): def __init__(self): origin = pathlib.Path(importlib.util.find_spec("ophyd").origin) module_file = str(origin.parent / "status.py") @@ -56,27 +74,18 @@ class _CustomImporter: f"{before}class StatusBase{orig_status_base}{_patched_status_base}class {final}" ) self.patched_code = compile(self.patched_source, module_file, "exec") + self.loader = _CustomLoader(self.patched_code) - def find_module(self, fullname, path): + def find_spec(self, fullname, path, target=None): + # The new import classes are difficult to grasp; + # why the finder needs a .loader member, it could be returned + # from here. And also .name, which name has to correspond to + # the searched module ??? if fullname == "ophyd.status": + self.name = fullname return self return None - def load_module(self, fullname, module_dict=None): - """Load and execute ophyd.status""" - status_module = ModuleType("ophyd.status") - status_module.__loader__ = self - status_module.__file__ = None - status_module.__name__ = fullname - - exec(self.patched_code, status_module.__dict__) - sys.modules[fullname] = status_module - - return status_module, True - - def get_source(self, fullname): - return self.patched_source - def monkey_patch_ophyd(): sys.meta_path.insert(0, _CustomImporter())