comparison mercurial/demandimport.py @ 15096:868282fa29d8

demandimport: determine at load time if __import__ has level argument
author Simon Heimberg <simohe@besonet.ch>
date Mon, 22 Aug 2011 22:50:52 +0200
parents 1dbd42a02153
children e3a5922e18c3
comparison
equal deleted inserted replaced
15093:2ca855126091 15096:868282fa29d8
26 26
27 import __builtin__ 27 import __builtin__
28 _origimport = __import__ 28 _origimport = __import__
29 29
30 nothing = object() 30 nothing = object()
31
32 try:
33 _origimport(__builtin__.__name__, {}, {}, None, -1)
34 except TypeError: # no level argument
35 def _import(name, globals, locals, fromlist, level):
36 "call _origimport with no level argument"
37 return _origimport(name, globals, locals, fromlist)
38 else:
39 _import = _origimport
31 40
32 class _demandmod(object): 41 class _demandmod(object):
33 """module demand-loader and proxy""" 42 """module demand-loader and proxy"""
34 def __init__(self, name, globals, locals): 43 def __init__(self, name, globals, locals):
35 if '.' in name: 44 if '.' in name:
81 setattr(self._module, attr, val) 90 setattr(self._module, attr, val)
82 91
83 def _demandimport(name, globals=None, locals=None, fromlist=None, level=-1): 92 def _demandimport(name, globals=None, locals=None, fromlist=None, level=-1):
84 if not locals or name in ignore or fromlist == ('*',): 93 if not locals or name in ignore or fromlist == ('*',):
85 # these cases we can't really delay 94 # these cases we can't really delay
86 if level == -1: 95 return _import(name, globals, locals, fromlist, level)
87 return _origimport(name, globals, locals, fromlist)
88 else:
89 return _origimport(name, globals, locals, fromlist, level)
90 elif not fromlist: 96 elif not fromlist:
91 # import a [as b] 97 # import a [as b]
92 if '.' in name: # a.b 98 if '.' in name: # a.b
93 base, rest = name.split('.', 1) 99 base, rest = name.split('.', 1)
94 # email.__init__ loading email.mime 100 # email.__init__ loading email.mime
95 if globals and globals.get('__name__', None) == base: 101 if globals and globals.get('__name__', None) == base:
96 if level != -1: 102 return _import(name, globals, locals, fromlist, level)
97 return _origimport(name, globals, locals, fromlist, level)
98 else:
99 return _origimport(name, globals, locals, fromlist)
100 # if a is already demand-loaded, add b to its submodule list 103 # if a is already demand-loaded, add b to its submodule list
101 if base in locals: 104 if base in locals:
102 if isinstance(locals[base], _demandmod): 105 if isinstance(locals[base], _demandmod):
103 locals[base]._extend(rest) 106 locals[base]._extend(rest)
104 return locals[base] 107 return locals[base]