-
Notifications
You must be signed in to change notification settings - Fork 16
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
19 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |