##// END OF EJS Templates
demandimport: fix TypeError when importing Python regex library (issue4920)
Gábor Stefanik -
r26830:65387a30 stable
parent child Browse files
Show More
@@ -1,265 +1,266 b''
1 # demandimport.py - global demand-loading of modules for Mercurial
1 # demandimport.py - global demand-loading of modules for Mercurial
2 #
2 #
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 '''
8 '''
9 demandimport - automatic demandloading of modules
9 demandimport - automatic demandloading of modules
10
10
11 To enable this module, do:
11 To enable this module, do:
12
12
13 import demandimport; demandimport.enable()
13 import demandimport; demandimport.enable()
14
14
15 Imports of the following forms will be demand-loaded:
15 Imports of the following forms will be demand-loaded:
16
16
17 import a, b.c
17 import a, b.c
18 import a.b as c
18 import a.b as c
19 from a import b,c # a will be loaded immediately
19 from a import b,c # a will be loaded immediately
20
20
21 These imports will not be delayed:
21 These imports will not be delayed:
22
22
23 from a import *
23 from a import *
24 b = __import__(a)
24 b = __import__(a)
25 '''
25 '''
26
26
27 from __future__ import absolute_import
27 from __future__ import absolute_import
28
28
29 import contextlib
29 import contextlib
30 import os
30 import os
31 import sys
31 import sys
32
32
33 # __builtin__ in Python 2, builtins in Python 3.
33 # __builtin__ in Python 2, builtins in Python 3.
34 try:
34 try:
35 import __builtin__ as builtins
35 import __builtin__ as builtins
36 except ImportError:
36 except ImportError:
37 import builtins
37 import builtins
38
38
39 contextmanager = contextlib.contextmanager
39 contextmanager = contextlib.contextmanager
40
40
41 _origimport = __import__
41 _origimport = __import__
42
42
43 nothing = object()
43 nothing = object()
44
44
45 # Python 3 doesn't have relative imports nor level -1.
45 # Python 3 doesn't have relative imports nor level -1.
46 level = -1
46 level = -1
47 if sys.version_info[0] >= 3:
47 if sys.version_info[0] >= 3:
48 level = 0
48 level = 0
49 _import = _origimport
49 _import = _origimport
50
50
51 def _hgextimport(importfunc, name, globals, *args, **kwargs):
51 def _hgextimport(importfunc, name, globals, *args, **kwargs):
52 try:
52 try:
53 return importfunc(name, globals, *args, **kwargs)
53 return importfunc(name, globals, *args, **kwargs)
54 except ImportError:
54 except ImportError:
55 if not globals:
55 if not globals:
56 raise
56 raise
57 # extensions are loaded with "hgext_" prefix
57 # extensions are loaded with "hgext_" prefix
58 hgextname = 'hgext_%s' % name
58 hgextname = 'hgext_%s' % name
59 nameroot = hgextname.split('.', 1)[0]
59 nameroot = hgextname.split('.', 1)[0]
60 contextroot = globals.get('__name__', '').split('.', 1)[0]
60 contextroot = globals.get('__name__', '').split('.', 1)[0]
61 if nameroot != contextroot:
61 if nameroot != contextroot:
62 raise
62 raise
63 # retry to import with "hgext_" prefix
63 # retry to import with "hgext_" prefix
64 return importfunc(hgextname, globals, *args, **kwargs)
64 return importfunc(hgextname, globals, *args, **kwargs)
65
65
66 class _demandmod(object):
66 class _demandmod(object):
67 """module demand-loader and proxy"""
67 """module demand-loader and proxy"""
68 def __init__(self, name, globals, locals, level=level):
68 def __init__(self, name, globals, locals, level=level):
69 if '.' in name:
69 if '.' in name:
70 head, rest = name.split('.', 1)
70 head, rest = name.split('.', 1)
71 after = [rest]
71 after = [rest]
72 else:
72 else:
73 head = name
73 head = name
74 after = []
74 after = []
75 object.__setattr__(self, "_data",
75 object.__setattr__(self, "_data",
76 (head, globals, locals, after, level, set()))
76 (head, globals, locals, after, level, set()))
77 object.__setattr__(self, "_module", None)
77 object.__setattr__(self, "_module", None)
78 def _extend(self, name):
78 def _extend(self, name):
79 """add to the list of submodules to load"""
79 """add to the list of submodules to load"""
80 self._data[3].append(name)
80 self._data[3].append(name)
81
81
82 def _addref(self, name):
82 def _addref(self, name):
83 """Record that the named module ``name`` imports this module.
83 """Record that the named module ``name`` imports this module.
84
84
85 References to this proxy class having the name of this module will be
85 References to this proxy class having the name of this module will be
86 replaced at module load time. We assume the symbol inside the importing
86 replaced at module load time. We assume the symbol inside the importing
87 module is identical to the "head" name of this module. We don't
87 module is identical to the "head" name of this module. We don't
88 actually know if "as X" syntax is being used to change the symbol name
88 actually know if "as X" syntax is being used to change the symbol name
89 because this information isn't exposed to __import__.
89 because this information isn't exposed to __import__.
90 """
90 """
91 self._data[5].add(name)
91 self._data[5].add(name)
92
92
93 def _load(self):
93 def _load(self):
94 if not self._module:
94 if not self._module:
95 head, globals, locals, after, level, modrefs = self._data
95 head, globals, locals, after, level, modrefs = self._data
96 mod = _hgextimport(_import, head, globals, locals, None, level)
96 mod = _hgextimport(_import, head, globals, locals, None, level)
97 # load submodules
97 # load submodules
98 def subload(mod, p):
98 def subload(mod, p):
99 h, t = p, None
99 h, t = p, None
100 if '.' in p:
100 if '.' in p:
101 h, t = p.split('.', 1)
101 h, t = p.split('.', 1)
102 if getattr(mod, h, nothing) is nothing:
102 if getattr(mod, h, nothing) is nothing:
103 setattr(mod, h, _demandmod(p, mod.__dict__, mod.__dict__))
103 setattr(mod, h, _demandmod(p, mod.__dict__, mod.__dict__))
104 elif t:
104 elif t:
105 subload(getattr(mod, h), t)
105 subload(getattr(mod, h), t)
106
106
107 for x in after:
107 for x in after:
108 subload(mod, x)
108 subload(mod, x)
109
109
110 # Replace references to this proxy instance with the actual module.
110 # Replace references to this proxy instance with the actual module.
111 if locals and locals.get(head) == self:
111 if locals and locals.get(head) == self:
112 locals[head] = mod
112 locals[head] = mod
113
113
114 for modname in modrefs:
114 for modname in modrefs:
115 modref = sys.modules.get(modname, None)
115 modref = sys.modules.get(modname, None)
116 if modref and getattr(modref, head, None) == self:
116 if modref and getattr(modref, head, None) == self:
117 setattr(modref, head, mod)
117 setattr(modref, head, mod)
118
118
119 object.__setattr__(self, "_module", mod)
119 object.__setattr__(self, "_module", mod)
120
120
121 def __repr__(self):
121 def __repr__(self):
122 if self._module:
122 if self._module:
123 return "<proxied module '%s'>" % self._data[0]
123 return "<proxied module '%s'>" % self._data[0]
124 return "<unloaded module '%s'>" % self._data[0]
124 return "<unloaded module '%s'>" % self._data[0]
125 def __call__(self, *args, **kwargs):
125 def __call__(self, *args, **kwargs):
126 raise TypeError("%s object is not callable" % repr(self))
126 raise TypeError("%s object is not callable" % repr(self))
127 def __getattribute__(self, attr):
127 def __getattribute__(self, attr):
128 if attr in ('_data', '_extend', '_load', '_module', '_addref'):
128 if attr in ('_data', '_extend', '_load', '_module', '_addref'):
129 return object.__getattribute__(self, attr)
129 return object.__getattribute__(self, attr)
130 self._load()
130 self._load()
131 return getattr(self._module, attr)
131 return getattr(self._module, attr)
132 def __setattr__(self, attr, val):
132 def __setattr__(self, attr, val):
133 self._load()
133 self._load()
134 setattr(self._module, attr, val)
134 setattr(self._module, attr, val)
135
135
136 def _demandimport(name, globals=None, locals=None, fromlist=None, level=level):
136 def _demandimport(name, globals=None, locals=None, fromlist=None, level=level):
137 if not locals or name in ignore or fromlist == ('*',):
137 if not locals or name in ignore or fromlist == ('*',):
138 # these cases we can't really delay
138 # these cases we can't really delay
139 return _hgextimport(_import, name, globals, locals, fromlist, level)
139 return _hgextimport(_import, name, globals, locals, fromlist, level)
140 elif not fromlist:
140 elif not fromlist:
141 # import a [as b]
141 # import a [as b]
142 if '.' in name: # a.b
142 if '.' in name: # a.b
143 base, rest = name.split('.', 1)
143 base, rest = name.split('.', 1)
144 # email.__init__ loading email.mime
144 # email.__init__ loading email.mime
145 if globals and globals.get('__name__', None) == base:
145 if globals and globals.get('__name__', None) == base:
146 return _import(name, globals, locals, fromlist, level)
146 return _import(name, globals, locals, fromlist, level)
147 # if a is already demand-loaded, add b to its submodule list
147 # if a is already demand-loaded, add b to its submodule list
148 if base in locals:
148 if base in locals:
149 if isinstance(locals[base], _demandmod):
149 if isinstance(locals[base], _demandmod):
150 locals[base]._extend(rest)
150 locals[base]._extend(rest)
151 return locals[base]
151 return locals[base]
152 return _demandmod(name, globals, locals, level)
152 return _demandmod(name, globals, locals, level)
153 else:
153 else:
154 # There is a fromlist.
154 # There is a fromlist.
155 # from a import b,c,d
155 # from a import b,c,d
156 # from . import b,c,d
156 # from . import b,c,d
157 # from .a import b,c,d
157 # from .a import b,c,d
158
158
159 # level == -1: relative and absolute attempted (Python 2 only).
159 # level == -1: relative and absolute attempted (Python 2 only).
160 # level >= 0: absolute only (Python 2 w/ absolute_import and Python 3).
160 # level >= 0: absolute only (Python 2 w/ absolute_import and Python 3).
161 # The modern Mercurial convention is to use absolute_import everywhere,
161 # The modern Mercurial convention is to use absolute_import everywhere,
162 # so modern Mercurial code will have level >= 0.
162 # so modern Mercurial code will have level >= 0.
163
163
164 # The name of the module the import statement is located in.
164 # The name of the module the import statement is located in.
165 globalname = globals.get('__name__')
165 globalname = globals.get('__name__')
166
166
167 def processfromitem(mod, attr, **kwargs):
167 def processfromitem(mod, attr, **kwargs):
168 """Process an imported symbol in the import statement.
168 """Process an imported symbol in the import statement.
169
169
170 If the symbol doesn't exist in the parent module, it must be a
170 If the symbol doesn't exist in the parent module, it must be a
171 module. We set missing modules up as _demandmod instances.
171 module. We set missing modules up as _demandmod instances.
172 """
172 """
173 symbol = getattr(mod, attr, nothing)
173 symbol = getattr(mod, attr, nothing)
174 if symbol is nothing:
174 if symbol is nothing:
175 symbol = _demandmod(attr, mod.__dict__, locals, **kwargs)
175 symbol = _demandmod(attr, mod.__dict__, locals, **kwargs)
176 setattr(mod, attr, symbol)
176 setattr(mod, attr, symbol)
177
177
178 # Record the importing module references this symbol so we can
178 # Record the importing module references this symbol so we can
179 # replace the symbol with the actual module instance at load
179 # replace the symbol with the actual module instance at load
180 # time.
180 # time.
181 if globalname and isinstance(symbol, _demandmod):
181 if globalname and isinstance(symbol, _demandmod):
182 symbol._addref(globalname)
182 symbol._addref(globalname)
183
183
184 if level >= 0:
184 if level >= 0:
185 # Mercurial's enforced import style does not use
185 # Mercurial's enforced import style does not use
186 # "from a import b,c,d" or "from .a import b,c,d" syntax. In
186 # "from a import b,c,d" or "from .a import b,c,d" syntax. In
187 # addition, this appears to be giving errors with some modules
187 # addition, this appears to be giving errors with some modules
188 # for unknown reasons. Since we shouldn't be using this syntax
188 # for unknown reasons. Since we shouldn't be using this syntax
189 # much, work around the problems.
189 # much, work around the problems.
190 if name:
190 if name:
191 return _hgextimport(_origimport, name, globals, locals,
191 return _hgextimport(_origimport, name, globals, locals,
192 fromlist, level)
192 fromlist, level)
193
193
194 mod = _hgextimport(_origimport, name, globals, locals, level=level)
194 mod = _hgextimport(_origimport, name, globals, locals, level=level)
195
195
196 for x in fromlist:
196 for x in fromlist:
197 processfromitem(mod, x, level=level)
197 processfromitem(mod, x, level=level)
198
198
199 return mod
199 return mod
200
200
201 # But, we still need to support lazy loading of standard library and 3rd
201 # But, we still need to support lazy loading of standard library and 3rd
202 # party modules. So handle level == -1.
202 # party modules. So handle level == -1.
203 mod = _hgextimport(_origimport, name, globals, locals)
203 mod = _hgextimport(_origimport, name, globals, locals)
204 # recurse down the module chain
204 # recurse down the module chain
205 for comp in name.split('.')[1:]:
205 for comp in name.split('.')[1:]:
206 if getattr(mod, comp, nothing) is nothing:
206 if getattr(mod, comp, nothing) is nothing:
207 setattr(mod, comp,
207 setattr(mod, comp,
208 _demandmod(comp, mod.__dict__, mod.__dict__))
208 _demandmod(comp, mod.__dict__, mod.__dict__))
209 mod = getattr(mod, comp)
209 mod = getattr(mod, comp)
210
210
211 for x in fromlist:
211 for x in fromlist:
212 processfromitem(mod, x)
212 processfromitem(mod, x)
213
213
214 return mod
214 return mod
215
215
216 ignore = [
216 ignore = [
217 '__future__',
217 '__future__',
218 '_hashlib',
218 '_hashlib',
219 '_xmlplus',
219 '_xmlplus',
220 'fcntl',
220 'fcntl',
221 'win32com.gen_py',
221 'win32com.gen_py',
222 '_winreg', # 2.7 mimetypes needs immediate ImportError
222 '_winreg', # 2.7 mimetypes needs immediate ImportError
223 'pythoncom',
223 'pythoncom',
224 # imported by tarfile, not available under Windows
224 # imported by tarfile, not available under Windows
225 'pwd',
225 'pwd',
226 'grp',
226 'grp',
227 # imported by profile, itself imported by hotshot.stats,
227 # imported by profile, itself imported by hotshot.stats,
228 # not available under Windows
228 # not available under Windows
229 'resource',
229 'resource',
230 # this trips up many extension authors
230 # this trips up many extension authors
231 'gtk',
231 'gtk',
232 # setuptools' pkg_resources.py expects "from __main__ import x" to
232 # setuptools' pkg_resources.py expects "from __main__ import x" to
233 # raise ImportError if x not defined
233 # raise ImportError if x not defined
234 '__main__',
234 '__main__',
235 '_ssl', # conditional imports in the stdlib, issue1964
235 '_ssl', # conditional imports in the stdlib, issue1964
236 '_sre', # issue4920
236 'rfc822',
237 'rfc822',
237 'mimetools',
238 'mimetools',
238 # setuptools 8 expects this module to explode early when not on windows
239 # setuptools 8 expects this module to explode early when not on windows
239 'distutils.msvc9compiler'
240 'distutils.msvc9compiler'
240 ]
241 ]
241
242
242 def isenabled():
243 def isenabled():
243 return builtins.__import__ == _demandimport
244 return builtins.__import__ == _demandimport
244
245
245 def enable():
246 def enable():
246 "enable global demand-loading of modules"
247 "enable global demand-loading of modules"
247 if os.environ.get('HGDEMANDIMPORT') != 'disable':
248 if os.environ.get('HGDEMANDIMPORT') != 'disable':
248 builtins.__import__ = _demandimport
249 builtins.__import__ = _demandimport
249
250
250 def disable():
251 def disable():
251 "disable global demand-loading of modules"
252 "disable global demand-loading of modules"
252 builtins.__import__ = _origimport
253 builtins.__import__ = _origimport
253
254
254 @contextmanager
255 @contextmanager
255 def deactivated():
256 def deactivated():
256 "context manager for disabling demandimport in 'with' blocks"
257 "context manager for disabling demandimport in 'with' blocks"
257 demandenabled = isenabled()
258 demandenabled = isenabled()
258 if demandenabled:
259 if demandenabled:
259 disable()
260 disable()
260
261
261 try:
262 try:
262 yield
263 yield
263 finally:
264 finally:
264 if demandenabled:
265 if demandenabled:
265 enable()
266 enable()
General Comments 0
You need to be logged in to leave comments. Login now