Skip to content
Myr

Copy pip's import machinery wholesale

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Ian Cordasco · committed by Ian Cordasco · parent e23bf10 · Browse files · 1 file+78 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+78 added−1 removed

  • other:+78 added−1 removed

1 file+78 added−1 removed

modified:requests/packages/__init__.py+78 added-1 removed
1"""2pip._vendor is for vendoring dependencies of pip to prevent needing pip to3depend on something external.45Files inside of pip._vendor should be considered immutable and should only be6updated to versions from upstream.7"""8from __future__ import absolute_import93from . import urllib310import sys111213class VendorAlias(object):1415 def __init__(self):16 self._vendor_name = __name__17 self._vendor_pkg = self._vendor_name + "."1819 def find_module(self, fullname, path=None):20 if fullname.startswith(self._vendor_pkg):21 return self2223 def load_module(self, name):24 # Ensure that this only works for the vendored name25 if not name.startswith(self._vendor_pkg):26 raise ImportError(27 "Cannot import %s, must be a subpackage of '%s'." % (28 name, self._vendor_name,29 )30 )3132 # Check to see if we already have this item in sys.modules, if we do33 # then simply return that.34 if name in sys.modules:35 return sys.modules[name]3637 # Check to see if we can import the vendor name38 try:39 # We do this dance here because we want to try and import this40 # module without hitting a recursion error because of a bunch of41 # VendorAlias instances on sys.meta_path42 real_meta_path = sys.meta_path[:]43 try:44 sys.meta_path = [45 m for m in sys.meta_path46 if not isinstance(m, VendorAlias)47 ]48 __import__(name)49 module = sys.modules[name]50 finally:51 # Re-add any additions to sys.meta_path that were made while52 # during the import we just did, otherwise things like53 # pip._vendor.six.moves will fail.54 for m in sys.meta_path:55 if m not in real_meta_path:56 real_meta_path.append(m)5758 # Restore sys.meta_path with any new items.59 sys.meta_path = real_meta_path60 except ImportError:61 # We can't import the vendor name, so we'll try to import the62 # "real" name.63 real_name = name[len(self._vendor_pkg):]64 try:65 __import__(real_name)66 module = sys.modules[real_name]67 except ImportError:68 raise ImportError("No module named '%s'" % (name,))6970 # If we've gotten here we've found the module we're looking for, either71 # as part of our vendored package, or as the real name, so we'll add72 # it to sys.modules as the vendored name so that we don't have to do73 # the lookup again.74 sys.modules[name] = module7576 # Finally, return the loaded module77 return module787980sys.meta_path.append(VendorAlias())