diff --git a/examples/libcalc/py_over_so.py b/examples/libcalc/py_over_so.py index b98699a3..b59af392 100644 --- a/examples/libcalc/py_over_so.py +++ b/examples/libcalc/py_over_so.py @@ -1,30 +1,19 @@ -# Copied from https://stackoverflow.com/questions/56074754/python-force-import-to-prefer-py-over-so -import glob, importlib, importlib.util, sys - -def hook(name): - if name != '.': - raise ImportError() - modnames = set(f.rstrip('.py') for f in glob.glob('*.py')) - return Finder(modnames) -sys.path_hooks.insert(1, hook) -sys.path.insert(0, '.') - -class Finder(object): - def __init__(self, modnames): - self.modnames = modnames - def find_spec(self, modname, target=None): - if modname in self.modnames: - origin = './' + modname + '.py' - loader = Loader() - return importlib.util.spec_from_loader(modname, loader, origin=origin) - else: - return None - -class Loader(object): - def create_module(self, target): - return None - def exec_module(self, module): - with open(module.__spec__.origin, 'r', encoding='utf-8') as f: - code = f.read() - compile(code, module.__spec__.origin, 'exec') - exec(code, module.__dict__) +from importlib.abc import Loader, MetaPathFinder +from importlib.util import module_from_spec, spec_from_file_location +import sys + + +overridden_modules = [] + + +def override_module(name): + overriden_modules += name + + +class PyFinder(MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname in overridden_modules: + return spec_from_file_location(fullname, "./%s.py" % fullname) + + +sys.meta_path.insert(0, PyFinder())