[PATCH] demandimport: determine at load time if __import__ has level argument

Simon Heimberg simohe at besonet.ch
Sun Sep 11 10:48:40 CDT 2011


# HG changeset patch
# User Simon Heimberg <simohe at besonet.ch>
# Date 1314046252 -7200
# Node ID b8c85c8448d70c2ae04f3c618b3aa628a2833198
# Parent  beb2d0a90f9037a470436c008876c8919504b917
demandimport: determine at load time if __import__ has level argument

diff -r beb2d0a90f90 -r b8c85c8448d7 mercurial/demandimport.py
--- a/mercurial/demandimport.py	Son Sep 11 17:48:11 2011 +0200
+++ b/mercurial/demandimport.py	Mon Aug 22 22:50:52 2011 +0200
@@ -29,6 +29,15 @@
 
 nothing = object()
 
+try:
+    _origimport(__builtin__.__name__, {}, {}, None, -1)
+except TypeError: # no level argument
+    def _import(name, globals, locals, fromlist, level):
+        "call _origimport with no level argument"
+        return _origimport(name, globals, locals, fromlist)
+else:
+    _import = _origimport
+
 class _demandmod(object):
     """module demand-loader and proxy"""
     def __init__(self, name, globals, locals):
@@ -83,20 +92,14 @@
 def _demandimport(name, globals=None, locals=None, fromlist=None, level=-1):
     if not locals or name in ignore or fromlist == ('*',):
         # these cases we can't really delay
-        if level == -1:
-            return _origimport(name, globals, locals, fromlist)
-        else:
-            return _origimport(name, globals, locals, fromlist, level)
+        return _import(name, globals, locals, fromlist, level)
     elif not fromlist:
         # import a [as b]
         if '.' in name: # a.b
             base, rest = name.split('.', 1)
             # email.__init__ loading email.mime
             if globals and globals.get('__name__', None) == base:
-                if level != -1:
-                    return _origimport(name, globals, locals, fromlist, level)
-                else:
-                    return _origimport(name, globals, locals, fromlist)
+                return _import(name, globals, locals, fromlist, level)
             # if a is already demand-loaded, add b to its submodule list
             if base in locals:
                 if isinstance(locals[base], _demandmod):


More information about the Mercurial-devel mailing list