demandimport: pass proper level to __import__ in Python 3
authorGregory Szorc <gregory.szorc@gmail.com>
Sat, 10 May 2014 14:57:25 -0700
changeset 21290 74be3fb1e3b8
parent 21289 c3784e3c3e8d
child 21291 007d276f8c94
demandimport: pass proper level to __import__ in Python 3 demandimport was failing in Python 3 with a ValueError because __import__'s level=-1 has gone away (-1 means to try both relative and absolute imports and relative imports don't exist in Python 3). With this patch, demandimport still doesn't work in Python 3 (it fails when importing a non-package module).
mercurial/demandimport.py
--- a/mercurial/demandimport.py	Wed Apr 16 19:55:40 2014 -0400
+++ b/mercurial/demandimport.py	Sat May 10 14:57:25 2014 -0700
@@ -24,13 +24,17 @@
   b = __import__(a)
 '''
 
-import __builtin__, os
+import __builtin__, os, sys
 _origimport = __import__
 
 nothing = object()
 
 try:
-    _origimport(__builtin__.__name__, {}, {}, None, -1)
+    # Python 3 doesn't have relative imports nor level -1.
+    level = -1
+    if sys.version_info[0] >= 3:
+        level = 0
+    _origimport(__builtin__.__name__, {}, {}, None, level)
 except TypeError: # no level argument
     def _import(name, globals, locals, fromlist, level):
         "call _origimport with no level argument"
@@ -55,7 +59,7 @@
 
 class _demandmod(object):
     """module demand-loader and proxy"""
-    def __init__(self, name, globals, locals, level=-1):
+    def __init__(self, name, globals, locals, level=level):
         if '.' in name:
             head, rest = name.split('.', 1)
             after = [rest]
@@ -105,7 +109,7 @@
         self._load()
         setattr(self._module, attr, val)
 
-def _demandimport(name, globals=None, locals=None, fromlist=None, level=-1):
+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
         return _hgextimport(_import, name, globals, locals, fromlist, level)