Created
February 12, 2020 20:57
-
-
Save charettes/2354364254f09bb69bd09b02d568d4ac to your computer and use it in GitHub Desktop.
Allow module aliasing
This file contains hidden or 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
from __future__ import unicode_literals | |
import re | |
import sys | |
from importlib import import_module | |
class _AliasLoader(object): | |
def __init__(self, alias, aliased): | |
self.alias = alias | |
self.aliased = aliased | |
def load_module(self, fullname): | |
aliased = fullname.replace(self.alias, self.aliased, 1) | |
return import_module(aliased) | |
class _AliasFinder(object): | |
def __init__(self, alias, aliased): | |
self.alias_pattern = re.compile(r'^({})\.?'.format(re.escape(alias))) | |
self.loader = _AliasLoader(alias, aliased) | |
def find_module(self, fullname, path=None): | |
if self.alias_pattern.match(fullname): | |
return self.loader | |
def alias_module(alias, aliased): | |
meta_path = _AliasFinder(alias, aliased) | |
sys.meta_path.append(meta_path) | |
return meta_path | |
alias_module('bongo', 'django') | |
from bongo.utils import six as bongo_six | |
from django.utils import six as django_six | |
assert bongo_six.assertRegex is django_six.assertRegex |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment