freeipa/ipaplatform/_importhook.py
Christian Heimes 7ddf7711f3 Use find_spec() in meta importer
The `find_module()` method of meta importers has been deprecated for a
long time. Python 3.12 no longer falls back to `find_module()`.

See: https://docs.python.org/3.12/whatsnew/3.12.html#removed
Related: https://pagure.io/freeipa/issue/9437
Signed-off-by: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Alexander Bokovoy <abbra@users.noreply.github.com>
2023-09-18 17:46:24 +02:00

52 lines
1.4 KiB
Python

#
# Copyright (C) 2017 FreeIPA Contributors see COPYING for license
#
from __future__ import absolute_import
import importlib
import sys
from ipaplatform.osinfo import osinfo
class IpaMetaImporter:
modules = {
'ipaplatform.constants',
'ipaplatform.paths',
'ipaplatform.services',
'ipaplatform.tasks'
}
def __init__(self, platform):
self.platform = platform
def find_spec(self, fullname, path=None, target=None):
"""Meta importer hook"""
if fullname in self.modules:
module = self.load_module(fullname)
return module.__spec__
return None
def load_module(self, fullname):
"""Meta importer hook"""
suffix = fullname.split('.', 1)[1]
alias = 'ipaplatform.{}.{}'.format(self.platform, suffix)
platform_mod = importlib.import_module(alias)
base_mod = sys.modules.get(fullname)
if base_mod is not None:
# module has been imported before, update its __dict__
base_mod.__dict__.update(platform_mod.__dict__)
for key in list(base_mod.__dict__):
if not hasattr(platform_mod, key):
delattr(base_mod, key)
else:
sys.modules[fullname] = platform_mod
return platform_mod
metaimporter = IpaMetaImporter(osinfo.platform)
sys.meta_path.insert(0, metaimporter)
fixup_module = metaimporter.load_module