Skip to content

Commit

Permalink
Try something else
Browse files Browse the repository at this point in the history
  • Loading branch information
kartik-s committed May 14, 2024
1 parent 899dcb8 commit b4335ee
Showing 1 changed file with 19 additions and 30 deletions.
49 changes: 19 additions & 30 deletions examples/libcalc/py_over_so.py
Original file line number Diff line number Diff line change
@@ -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())

0 comments on commit b4335ee

Please sign in to comment.