# HG changeset patch # User Bryan O'Sullivan # Date 2015-12-24 00:22:20 # Node ID f7d890bc5e01592186b913b68437202ce8daaff8 # Parent 0d0f4070f6d7cee9bb86b7f3ac2e81a719183b81 demandimport: add support for PyPy PyPy's implementation of __import__ differs subtly from that of CPython. If invoked without a name or fromlist, it throws an ImportError, whereas CPython returns a reference to the level-appropriate importing package. Here, we achieve the same behaviour by hand. diff --git a/mercurial/demandimport.py b/mercurial/demandimport.py --- a/mercurial/demandimport.py +++ b/mercurial/demandimport.py @@ -133,6 +133,8 @@ class _demandmod(object): self._load() setattr(self._module, attr, val) +_pypy = '__pypy__' in sys.builtin_module_names + def _demandimport(name, globals=None, locals=None, fromlist=None, level=level): if not locals or name in ignore or fromlist == ('*',): # these cases we can't really delay @@ -191,7 +193,21 @@ def _demandimport(name, globals=None, lo return _hgextimport(_origimport, name, globals, locals, fromlist, level) - mod = _hgextimport(_origimport, name, globals, locals, level=level) + if _pypy: + # PyPy's __import__ throws an exception if invoked + # with an empty name and no fromlist. Recreate the + # desired behaviour by hand. + mn = globalname + mod = sys.modules[mn] + if getattr(mod, '__path__', nothing) is nothing: + mn = mn.rsplit('.', 1)[0] + mod = sys.modules[mn] + if level > 1: + mn = mn.rsplit('.', level - 1)[0] + mod = sys.modules[mn] + else: + mod = _hgextimport(_origimport, name, globals, locals, + level=level) for x in fromlist: processfromitem(mod, x) @@ -245,10 +261,6 @@ def isenabled(): def enable(): "enable global demand-loading of modules" - # PyPy doesn't work with demand import. - if '__pypy__' in sys.builtin_module_names: - return - if os.environ.get('HGDEMANDIMPORT') != 'disable': builtins.__import__ = _demandimport