changeset 21290:74be3fb1e3b8

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).
author Gregory Szorc <gregory.szorc@gmail.com>
date Sat, 10 May 2014 14:57:25 -0700
parents c3784e3c3e8d
children 007d276f8c94
files mercurial/demandimport.py
diffstat 1 files changed, 8 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- 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)