Last active
August 29, 2015 14:03
-
-
Save mdevaev/b7eb44fc7d96d4f5414b to your computer and use it in GitHub Desktop.
Import module from path
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
import sys | |
import importlib.abc | |
# ===== | |
def setup(*args, **kwargs): | |
finder = _Finder(*args, **kwargs) | |
sys.meta_path = [finder] + sys.meta_path | |
return finder | |
def remove(finder): | |
sys.meta_path.remove(finder) | |
# ===== | |
class _Finder(importlib.abc.Finder): | |
def __init__(self, root_name, get_path): | |
assert callable(get_path), "get_path() must be a callable" | |
self._root_name = root_name | |
self._get_path = get_path | |
def find_module(self, fullname, path=None): | |
if fullname.split(".")[0] == self._root_name: | |
if sys.version_info[:2] == (3, 2): # PyPy/Python 3.2 hacks | |
import importlib._bootstrap # pylint: disable=W0621 | |
finder = importlib._bootstrap._file_path_hook(self._get_path()) # pylint: disable=W0212 | |
return finder.find_module(fullname) | |
elif sys.version_info[:2] == (3, 4): # Python 3.4 | |
import importlib.machinery | |
finder = importlib.machinery.PathFinder | |
return finder.find_module(fullname, [self._get_path()]) | |
else: | |
RuntimeError("No importlib hacks for your Python: {}".format(sys.version_info)) | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test: