blob: 98361a77b9c8605c9520a16e24ffd4729e04ede1 [file] [log] [blame]
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001"""Core implementation of import.
2
3This module is NOT meant to be directly imported! It has been designed such
4that it can be bootstrapped into Python as the implementation of import. As
5such it requires the injection of specific modules and attributes in order to
6work. One should use importlib as the public-facing version of this module.
7
8"""
Marc-Andre Lemburg7541c8e2012-04-25 10:54:48 +02009#
10# IMPORTANT: Whenever making changes to this module, be sure to run
11# a top-level make in order to get the frozen version of the module
12# update. Not doing so, will result in the Makefile to fail for
13# all others who don't have a ./python around to freeze the module
14# in the early stages of compilation.
15#
Brett Cannon23cbd8a2009-01-18 00:24:28 +000016
Brett Cannoned672d62012-04-20 21:19:53 -040017# See importlib._setup() for what is injected into the global namespace.
18
Brett Cannon23cbd8a2009-01-18 00:24:28 +000019# When editing this code be aware that code executed at import time CANNOT
20# reference any injected objects! This includes not only global code but also
21# anything specified at the class level.
22
Brett Cannon938d44d2012-04-22 19:58:33 -040023# XXX Make sure all public names have no single leading underscore and all
24# others do.
25
Brett Cannon23cbd8a2009-01-18 00:24:28 +000026
Brett Cannonce43ddf2009-03-12 22:28:55 +000027# Bootstrap-related code ######################################################
28
Brett Cannon17098a52012-05-04 13:52:49 -040029_CASE_INSENSITIVE_PLATFORMS = 'win', 'cygwin', 'darwin'
Brett Cannon51d14f82012-01-26 19:03:52 -050030
Brett Cannon51d14f82012-01-26 19:03:52 -050031
Antoine Pitroub67075b2012-02-20 13:52:47 +010032def _make_relax_case():
Brett Cannon17098a52012-05-04 13:52:49 -040033 if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
Antoine Pitrouc541f8e2012-02-20 01:48:16 +010034 def _relax_case():
Benjamin Peterson6ddac002012-02-20 15:06:35 -050035 """True if filenames must be checked case-insensitively."""
Antoine Pitrouc541f8e2012-02-20 01:48:16 +010036 return b'PYTHONCASEOK' in _os.environ
Brett Cannon51d14f82012-01-26 19:03:52 -050037 else:
Antoine Pitrouc541f8e2012-02-20 01:48:16 +010038 def _relax_case():
Benjamin Peterson6ddac002012-02-20 15:06:35 -050039 """True if filenames must be checked case-insensitively."""
Antoine Pitrouc541f8e2012-02-20 01:48:16 +010040 return False
41 return _relax_case
Brett Cannon51d14f82012-01-26 19:03:52 -050042
43
Brett Cannonc264e3e2012-01-25 18:58:03 -050044# TODO: Expose from marshal
45def _w_long(x):
46 """Convert a 32-bit integer to little-endian.
47
48 XXX Temporary until marshal's long functions are exposed.
49
50 """
51 x = int(x)
52 int_bytes = []
53 int_bytes.append(x & 0xFF)
54 int_bytes.append((x >> 8) & 0xFF)
55 int_bytes.append((x >> 16) & 0xFF)
56 int_bytes.append((x >> 24) & 0xFF)
57 return bytearray(int_bytes)
58
59
60# TODO: Expose from marshal
61def _r_long(int_bytes):
62 """Convert 4 bytes in little-endian to an integer.
63
64 XXX Temporary until marshal's long function are exposed.
65
66 """
67 x = int_bytes[0]
68 x |= int_bytes[1] << 8
69 x |= int_bytes[2] << 16
70 x |= int_bytes[3] << 24
71 return x
72
73
Brett Cannon5c903e62012-04-22 11:45:07 -040074def _path_join(*path_parts):
Brett Cannoned672d62012-04-20 21:19:53 -040075 """Replacement for os.path.join()."""
Brett Cannon5c903e62012-04-22 11:45:07 -040076 new_parts = []
77 for part in path_parts:
78 if not part:
79 continue
80 new_parts.append(part)
81 if part[-1] not in path_separators:
82 new_parts.append(path_sep)
83 return ''.join(new_parts[:-1]) # Drop superfluous path separator.
Brett Cannoned672d62012-04-20 21:19:53 -040084
85
86def _path_split(path):
87 """Replacement for os.path.split()."""
88 for x in reversed(path):
89 if x in path_separators:
90 sep = x
91 break
92 else:
93 sep = path_sep
94 front, _, tail = path.rpartition(sep)
95 return front, tail
Brett Cannon23cbd8a2009-01-18 00:24:28 +000096
97
Brett Cannon23cbd8a2009-01-18 00:24:28 +000098def _path_is_mode_type(path, mode):
99 """Test whether the path is the specified mode type."""
100 try:
101 stat_info = _os.stat(path)
102 except OSError:
103 return False
104 return (stat_info.st_mode & 0o170000) == mode
105
106
107# XXX Could also expose Modules/getpath.c:isfile()
108def _path_isfile(path):
109 """Replacement for os.path.isfile."""
110 return _path_is_mode_type(path, 0o100000)
111
112
113# XXX Could also expose Modules/getpath.c:isdir()
114def _path_isdir(path):
115 """Replacement for os.path.isdir."""
Brett Cannon61b14252010-07-03 21:48:25 +0000116 if not path:
117 path = _os.getcwd()
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000118 return _path_is_mode_type(path, 0o040000)
119
120
Nick Coghlana5087702012-08-24 18:32:40 +1000121def _write_atomic(path, data, mode=0o666):
Charles-François Natali6db1c402012-02-22 21:03:09 +0100122 """Best-effort function to write data to a path atomically.
123 Be prepared to handle a FileExistsError if concurrent writing of the
124 temporary file is attempted."""
Antoine Pitrou28e401e2011-11-15 19:15:19 +0100125 # id() is used to generate a pseudo-random filename.
126 path_tmp = '{}.{}'.format(path, id(path))
Nick Coghlana5087702012-08-24 18:32:40 +1000127 fd = _os.open(path_tmp,
128 _os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, mode & 0o666)
Antoine Pitrou28e401e2011-11-15 19:15:19 +0100129 try:
Brett Cannonba17fe22012-02-17 09:26:53 -0500130 # We first write data to a temporary file, and then use os.replace() to
131 # perform an atomic rename.
Antoine Pitrou28e401e2011-11-15 19:15:19 +0100132 with _io.FileIO(fd, 'wb') as file:
Antoine Pitrou707033a2011-10-17 19:28:44 +0200133 file.write(data)
Brett Cannonba17fe22012-02-17 09:26:53 -0500134 _os.replace(path_tmp, path)
Antoine Pitrou28e401e2011-11-15 19:15:19 +0100135 except OSError:
136 try:
137 _os.unlink(path_tmp)
138 except OSError:
139 pass
140 raise
Antoine Pitrou707033a2011-10-17 19:28:44 +0200141
142
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000143def _wrap(new, old):
Florent Xicluna79d79a02012-07-07 13:16:44 +0200144 """Simple substitute for functools.update_wrapper."""
Meador Inge96ff0842011-12-14 22:53:13 -0600145 for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
Brett Cannon8490fab2012-02-08 18:44:14 -0500146 if hasattr(old, replace):
147 setattr(new, replace, getattr(old, replace))
Brett Cannon51d8bfc2009-02-07 02:13:28 +0000148 new.__dict__.update(old.__dict__)
149
150
Brett Cannon17098a52012-05-04 13:52:49 -0400151_code_type = type(_wrap.__code__)
Brett Cannon61b14252010-07-03 21:48:25 +0000152
Brett Cannon6f44d662012-04-15 16:08:47 -0400153
Brett Cannon17098a52012-05-04 13:52:49 -0400154def new_module(name):
Brett Cannon6f44d662012-04-15 16:08:47 -0400155 """Create a new module.
156
157 The module is not entered into sys.modules.
158
159 """
Brett Cannonf19c1912012-05-04 15:46:04 -0400160 return type(_io)(name)
Brett Cannon6f44d662012-04-15 16:08:47 -0400161
162
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200163# Module-level locking ########################################################
164
165# A dict mapping module names to weakrefs of _ModuleLock instances
166_module_locks = {}
167# A dict mapping thread ids to _ModuleLock instances
168_blocking_on = {}
169
170
171class _DeadlockError(RuntimeError):
172 pass
173
174
175class _ModuleLock:
176 """A recursive lock implementation which is able to detect deadlocks
177 (e.g. thread 1 trying to take locks A then B, and thread 2 trying to
178 take locks B then A).
179 """
180
181 def __init__(self, name):
182 self.lock = _thread.allocate_lock()
183 self.wakeup = _thread.allocate_lock()
184 self.name = name
185 self.owner = None
186 self.count = 0
187 self.waiters = 0
188
189 def has_deadlock(self):
190 # Deadlock avoidance for concurrent circular imports.
191 me = _thread.get_ident()
192 tid = self.owner
193 while True:
194 lock = _blocking_on.get(tid)
195 if lock is None:
196 return False
197 tid = lock.owner
198 if tid == me:
199 return True
200
201 def acquire(self):
202 """
203 Acquire the module lock. If a potential deadlock is detected,
204 a _DeadlockError is raised.
205 Otherwise, the lock is always acquired and True is returned.
206 """
207 tid = _thread.get_ident()
208 _blocking_on[tid] = self
209 try:
210 while True:
211 with self.lock:
212 if self.count == 0 or self.owner == tid:
213 self.owner = tid
214 self.count += 1
215 return True
216 if self.has_deadlock():
217 raise _DeadlockError("deadlock detected by %r" % self)
218 if self.wakeup.acquire(False):
219 self.waiters += 1
220 # Wait for a release() call
221 self.wakeup.acquire()
222 self.wakeup.release()
223 finally:
224 del _blocking_on[tid]
225
226 def release(self):
227 tid = _thread.get_ident()
228 with self.lock:
229 if self.owner != tid:
230 raise RuntimeError("cannot release un-acquired lock")
231 assert self.count > 0
232 self.count -= 1
233 if self.count == 0:
234 self.owner = None
235 if self.waiters:
236 self.waiters -= 1
237 self.wakeup.release()
238
239 def __repr__(self):
240 return "_ModuleLock(%r) at %d" % (self.name, id(self))
241
242
243class _DummyModuleLock:
244 """A simple _ModuleLock equivalent for Python builds without
245 multi-threading support."""
246
247 def __init__(self, name):
248 self.name = name
249 self.count = 0
250
251 def acquire(self):
252 self.count += 1
253 return True
254
255 def release(self):
256 if self.count == 0:
257 raise RuntimeError("cannot release un-acquired lock")
258 self.count -= 1
259
260 def __repr__(self):
261 return "_DummyModuleLock(%r) at %d" % (self.name, id(self))
262
263
264# The following two functions are for consumption by Python/import.c.
265
266def _get_module_lock(name):
267 """Get or create the module lock for a given module name.
268
269 Should only be called with the import lock taken."""
270 lock = None
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200271 try:
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200272 lock = _module_locks[name]()
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200273 except KeyError:
274 pass
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200275 if lock is None:
276 if _thread is None:
277 lock = _DummyModuleLock(name)
278 else:
279 lock = _ModuleLock(name)
280 def cb(_):
281 del _module_locks[name]
282 _module_locks[name] = _weakref.ref(lock, cb)
283 return lock
284
285def _lock_unlock_module(name):
286 """Release the global import lock, and acquires then release the
287 module lock for a given module name.
288 This is used to ensure a module is completely initialized, in the
289 event it is being imported by another thread.
290
291 Should only be called with the import lock taken."""
292 lock = _get_module_lock(name)
293 _imp.release_lock()
294 try:
295 lock.acquire()
296 except _DeadlockError:
297 # Concurrent circular import, we'll accept a partially initialized
298 # module object.
299 pass
300 else:
301 lock.release()
302
Nick Coghlan42c07662012-07-31 21:14:18 +1000303# Frame stripping magic ###############################################
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200304
Nick Coghlan42c07662012-07-31 21:14:18 +1000305def _call_with_frames_removed(f, *args, **kwds):
306 """remove_importlib_frames in import.c will always remove sequences
307 of importlib frames that end with a call to this function
308
309 Use it instead of a normal call in places where including the importlib
310 frames introduces unwanted noise into the traceback (e.g. when executing
311 module code)
312 """
313 return f(*args, **kwds)
314
315
316# Finder/loader utility code ###############################################
Brett Cannonce43ddf2009-03-12 22:28:55 +0000317
Brett Cannon77b2abd2012-07-09 16:09:00 -0400318"""Magic word to reject .pyc files generated by other Python versions.
319It should change for each incompatible change to the bytecode.
320
321The value of CR and LF is incorporated so if you ever read or write
322a .pyc file in text mode the magic number will be wrong; also, the
323Apple MPW compiler swaps their values, botching string constants.
324
325The magic numbers must be spaced apart at least 2 values, as the
326-U interpeter flag will cause MAGIC+1 being used. They have been
327odd numbers for some time now.
328
329There were a variety of old schemes for setting the magic number.
330The current working scheme is to increment the previous value by
33110.
332
333Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
334number also includes a new "magic tag", i.e. a human readable string used
335to represent the magic number in __pycache__ directories. When you change
336the magic number, you must also set a new unique magic tag. Generally this
337can be named after the Python major version of the magic number bump, but
338it can really be anything, as long as it's different than anything else
339that's come before. The tags are included in the following table, starting
340with Python 3.2a0.
341
342Known values:
343 Python 1.5: 20121
344 Python 1.5.1: 20121
345 Python 1.5.2: 20121
346 Python 1.6: 50428
347 Python 2.0: 50823
348 Python 2.0.1: 50823
349 Python 2.1: 60202
350 Python 2.1.1: 60202
351 Python 2.1.2: 60202
352 Python 2.2: 60717
353 Python 2.3a0: 62011
354 Python 2.3a0: 62021
355 Python 2.3a0: 62011 (!)
356 Python 2.4a0: 62041
357 Python 2.4a3: 62051
358 Python 2.4b1: 62061
359 Python 2.5a0: 62071
360 Python 2.5a0: 62081 (ast-branch)
361 Python 2.5a0: 62091 (with)
362 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
363 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
364 Python 2.5b3: 62111 (fix wrong code: x += yield)
365 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
366 storing constants that should have been removed)
367 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
368 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
369 Python 2.6a1: 62161 (WITH_CLEANUP optimization)
370 Python 3000: 3000
371 3010 (removed UNARY_CONVERT)
372 3020 (added BUILD_SET)
373 3030 (added keyword-only parameters)
374 3040 (added signature annotations)
375 3050 (print becomes a function)
376 3060 (PEP 3115 metaclass syntax)
377 3061 (string literals become unicode)
378 3071 (PEP 3109 raise changes)
379 3081 (PEP 3137 make __file__ and __name__ unicode)
380 3091 (kill str8 interning)
381 3101 (merge from 2.6a0, see 62151)
382 3103 (__file__ points to source file)
383 Python 3.0a4: 3111 (WITH_CLEANUP optimization).
384 Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
385 Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
386 change LIST_APPEND and SET_ADD, add MAP_ADD)
387 Python 3.1a0: 3151 (optimize conditional branches:
388 introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
389 Python 3.2a0: 3160 (add SETUP_WITH)
390 tag: cpython-32
391 Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
392 tag: cpython-32
393 Python 3.2a2 3180 (add DELETE_DEREF)
394 Python 3.3a0 3190 __class__ super closure changed
395 Python 3.3a0 3200 (__qualname__ added)
396 3210 (added size modulo 2**32 to the pyc header)
397 Python 3.3a1 3220 (changed PEP 380 implementation)
398 Python 3.3a4 3230 (revert changes to implicit __class__ closure)
399
400MAGIC must change whenever the bytecode emitted by the compiler may no
401longer be understood by older implementations of the eval loop (usually
402due to the addition of new opcodes).
403
404"""
405_RAW_MAGIC_NUMBER = 3230 | ord('\r') << 16 | ord('\n') << 24
406_MAGIC_BYTES = bytes(_RAW_MAGIC_NUMBER >> n & 0xff for n in range(0, 25, 8))
407
Brett Cannon17098a52012-05-04 13:52:49 -0400408_PYCACHE = '__pycache__'
Brett Cannonea59dbf2012-04-20 21:44:46 -0400409
Brett Cannoncb66eb02012-05-11 12:58:42 -0400410SOURCE_SUFFIXES = ['.py'] # _setup() adds .pyw as needed.
Brett Cannona64faf02012-04-21 18:52:52 -0400411
Brett Cannoncb66eb02012-05-11 12:58:42 -0400412DEBUG_BYTECODE_SUFFIXES = ['.pyc']
413OPTIMIZED_BYTECODE_SUFFIXES = ['.pyo']
Brett Cannonea59dbf2012-04-20 21:44:46 -0400414
Brett Cannon17098a52012-05-04 13:52:49 -0400415def cache_from_source(path, debug_override=None):
Brett Cannonea59dbf2012-04-20 21:44:46 -0400416 """Given the path to a .py file, return the path to its .pyc/.pyo file.
417
418 The .py file does not need to exist; this simply returns the path to the
419 .pyc/.pyo file calculated as if the .py file were imported. The extension
Benjamin Petersonfeaa54f2012-09-25 11:22:59 -0400420 will be .pyc unless sys.flags.optimize is non-zero, then it will be .pyo.
Brett Cannonea59dbf2012-04-20 21:44:46 -0400421
Benjamin Peterson52c62d82012-09-26 00:25:10 -0400422 If debug_override is not None, then it must be a boolean and is used in
423 place of sys.flags.optimize.
Brett Cannonea59dbf2012-04-20 21:44:46 -0400424
Brett Cannon19a2f592012-07-09 13:58:07 -0400425 If sys.implementation.cache_tag is None then NotImplementedError is raised.
426
Brett Cannonea59dbf2012-04-20 21:44:46 -0400427 """
Benjamin Petersonfeaa54f2012-09-25 11:22:59 -0400428 debug = not sys.flags.optimize if debug_override is None else debug_override
Brett Cannoncb66eb02012-05-11 12:58:42 -0400429 if debug:
430 suffixes = DEBUG_BYTECODE_SUFFIXES
431 else:
432 suffixes = OPTIMIZED_BYTECODE_SUFFIXES
Brett Cannonea59dbf2012-04-20 21:44:46 -0400433 head, tail = _path_split(path)
434 base_filename, sep, _ = tail.partition('.')
Brett Cannon19a2f592012-07-09 13:58:07 -0400435 tag = sys.implementation.cache_tag
436 if tag is None:
437 raise NotImplementedError('sys.implementation.cache_tag is None')
438 filename = ''.join([base_filename, sep, tag, suffixes[0]])
Brett Cannon17098a52012-05-04 13:52:49 -0400439 return _path_join(head, _PYCACHE, filename)
Brett Cannonea59dbf2012-04-20 21:44:46 -0400440
441
Brett Cannona6473f92012-07-13 13:57:03 -0400442def source_from_cache(path):
443 """Given the path to a .pyc./.pyo file, return the path to its .py file.
444
445 The .pyc/.pyo file does not need to exist; this simply returns the path to
446 the .py file calculated to correspond to the .pyc/.pyo file. If path does
447 not conform to PEP 3147 format, ValueError will be raised. If
448 sys.implementation.cache_tag is None then NotImplementedError is raised.
449
450 """
451 if sys.implementation.cache_tag is None:
452 raise NotImplementedError('sys.implementation.cache_tag is None')
453 head, pycache_filename = _path_split(path)
454 head, pycache = _path_split(head)
455 if pycache != _PYCACHE:
456 raise ValueError('{} not bottom-level directory in '
457 '{!r}'.format(_PYCACHE, path))
458 if pycache_filename.count('.') != 2:
459 raise ValueError('expected only 2 dots in '
460 '{!r}'.format(pycache_filename))
461 base_filename = pycache_filename.partition('.')[0]
462 return _path_join(head, base_filename + SOURCE_SUFFIXES[0])
463
464
465def _get_sourcefile(bytecode_path):
466 """Convert a bytecode file path to a source path (if possible).
467
468 This function exists purely for backwards-compatibility for
469 PyImport_ExecCodeModuleWithFilenames() in the C API.
470
471 """
472 if len(bytecode_path) == 0:
473 return None
474 rest, _, extension = bytecode_path.rparition('.')
475 if not rest or extension.lower()[-3:-1] != '.py':
476 return bytecode_path
477
478 try:
479 source_path = source_from_cache(bytecode_path)
480 except (NotImplementedError, ValueError):
481 source_path = bytcode_path[-1:]
482
483 return source_path if _path_isfile(source_stats) else bytecode_path
484
485
Brett Cannon17098a52012-05-04 13:52:49 -0400486def _verbose_message(message, *args):
Brett Cannonfd074152012-04-14 14:10:13 -0400487 """Print the message to stderr if -v/PYTHONVERBOSE is turned on."""
488 if sys.flags.verbose:
Philip Jenveyf8f31902012-04-15 12:21:32 -0700489 if not message.startswith(('#', 'import ')):
Brett Cannonfd074152012-04-14 14:10:13 -0400490 message = '# ' + message
491 print(message.format(*args), file=sys.stderr)
492
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100493
Brett Cannon435aad82009-03-04 16:07:00 +0000494def set_package(fxn):
Brett Cannon06c9d962009-02-07 01:52:25 +0000495 """Set __package__ on the returned module."""
Brett Cannonf522aea2012-01-16 11:46:22 -0500496 def set_package_wrapper(*args, **kwargs):
Brett Cannon06c9d962009-02-07 01:52:25 +0000497 module = fxn(*args, **kwargs)
Florent Xicluna79d79a02012-07-07 13:16:44 +0200498 if getattr(module, '__package__', None) is None:
Brett Cannon06c9d962009-02-07 01:52:25 +0000499 module.__package__ = module.__name__
500 if not hasattr(module, '__path__'):
501 module.__package__ = module.__package__.rpartition('.')[0]
502 return module
Brett Cannonf522aea2012-01-16 11:46:22 -0500503 _wrap(set_package_wrapper, fxn)
504 return set_package_wrapper
Brett Cannon06c9d962009-02-07 01:52:25 +0000505
506
Brett Cannon2cf03a82009-03-10 05:17:37 +0000507def set_loader(fxn):
508 """Set __loader__ on the returned module."""
Brett Cannonf522aea2012-01-16 11:46:22 -0500509 def set_loader_wrapper(self, *args, **kwargs):
Brett Cannon2cf03a82009-03-10 05:17:37 +0000510 module = fxn(self, *args, **kwargs)
511 if not hasattr(module, '__loader__'):
512 module.__loader__ = self
513 return module
Brett Cannonf522aea2012-01-16 11:46:22 -0500514 _wrap(set_loader_wrapper, fxn)
515 return set_loader_wrapper
Brett Cannon2cf03a82009-03-10 05:17:37 +0000516
517
Brett Cannonce43ddf2009-03-12 22:28:55 +0000518def module_for_loader(fxn):
519 """Decorator to handle selecting the proper module for loaders.
520
Brett Cannon0e0d8a62009-03-15 00:00:19 +0000521 The decorated function is passed the module to use instead of the module
522 name. The module passed in to the function is either from sys.modules if
Brett Cannonefad00d2012-04-27 17:27:14 -0400523 it already exists or is a new module. If the module is new, then __name__
524 is set the first argument to the method, __loader__ is set to self, and
525 __package__ is set accordingly (if self.is_package() is defined) will be set
526 before it is passed to the decorated function (if self.is_package() does
527 not work for the module it will be set post-load).
528
529 If an exception is raised and the decorator created the module it is
530 subsequently removed from sys.modules.
Brett Cannonce43ddf2009-03-12 22:28:55 +0000531
Brett Cannon0e0d8a62009-03-15 00:00:19 +0000532 The decorator assumes that the decorated function takes the module name as
533 the second argument.
Brett Cannonce43ddf2009-03-12 22:28:55 +0000534
535 """
Brett Cannonf522aea2012-01-16 11:46:22 -0500536 def module_for_loader_wrapper(self, fullname, *args, **kwargs):
Brett Cannonce43ddf2009-03-12 22:28:55 +0000537 module = sys.modules.get(fullname)
Brett Cannon7bd329d2012-04-17 21:41:35 -0400538 is_reload = module is not None
Brett Cannonce43ddf2009-03-12 22:28:55 +0000539 if not is_reload:
540 # This must be done before open() is called as the 'io' module
541 # implicitly imports 'locale' and would otherwise trigger an
542 # infinite loop.
Brett Cannon17098a52012-05-04 13:52:49 -0400543 module = new_module(fullname)
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200544 # This must be done before putting the module in sys.modules
545 # (otherwise an optimization shortcut in import.c becomes wrong)
546 module.__initializing__ = True
Brett Cannonce43ddf2009-03-12 22:28:55 +0000547 sys.modules[fullname] = module
Brett Cannonefad00d2012-04-27 17:27:14 -0400548 module.__loader__ = self
549 try:
550 is_package = self.is_package(fullname)
551 except (ImportError, AttributeError):
552 pass
553 else:
554 if is_package:
555 module.__package__ = fullname
556 else:
557 module.__package__ = fullname.rpartition('.')[0]
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200558 else:
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200559 module.__initializing__ = True
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200560 try:
Brett Cannonefad00d2012-04-27 17:27:14 -0400561 # If __package__ was not set above, __import__() will do it later.
Brett Cannon61b14252010-07-03 21:48:25 +0000562 return fxn(self, module, *args, **kwargs)
Brett Cannonce43ddf2009-03-12 22:28:55 +0000563 except:
564 if not is_reload:
565 del sys.modules[fullname]
566 raise
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200567 finally:
568 module.__initializing__ = False
Brett Cannonf522aea2012-01-16 11:46:22 -0500569 _wrap(module_for_loader_wrapper, fxn)
570 return module_for_loader_wrapper
Brett Cannonce43ddf2009-03-12 22:28:55 +0000571
572
573def _check_name(method):
574 """Decorator to verify that the module being requested matches the one the
575 loader can handle.
576
577 The first argument (self) must define _name which the second argument is
Ezio Melotti42da6632011-03-15 05:18:48 +0200578 compared against. If the comparison fails then ImportError is raised.
Brett Cannonce43ddf2009-03-12 22:28:55 +0000579
580 """
Brett Cannonc0499522012-05-11 14:48:41 -0400581 def _check_name_wrapper(self, name=None, *args, **kwargs):
582 if name is None:
583 name = self.name
584 elif self.name != name:
Brett Cannonbbb66802012-04-12 21:09:01 -0400585 raise ImportError("loader cannot handle %s" % name, name=name)
Brett Cannonce43ddf2009-03-12 22:28:55 +0000586 return method(self, name, *args, **kwargs)
Brett Cannonf522aea2012-01-16 11:46:22 -0500587 _wrap(_check_name_wrapper, method)
588 return _check_name_wrapper
Brett Cannonce43ddf2009-03-12 22:28:55 +0000589
590
Brett Cannona113ac52009-03-15 01:41:33 +0000591def _requires_builtin(fxn):
592 """Decorator to verify the named module is built-in."""
Brett Cannonf522aea2012-01-16 11:46:22 -0500593 def _requires_builtin_wrapper(self, fullname):
Brett Cannona113ac52009-03-15 01:41:33 +0000594 if fullname not in sys.builtin_module_names:
Florent Xicluna79d79a02012-07-07 13:16:44 +0200595 raise ImportError("{} is not a built-in module".format(fullname),
Brett Cannonbbb66802012-04-12 21:09:01 -0400596 name=fullname)
Brett Cannona113ac52009-03-15 01:41:33 +0000597 return fxn(self, fullname)
Brett Cannonf522aea2012-01-16 11:46:22 -0500598 _wrap(_requires_builtin_wrapper, fxn)
599 return _requires_builtin_wrapper
Brett Cannona113ac52009-03-15 01:41:33 +0000600
601
Brett Cannon8d110132009-03-15 02:20:16 +0000602def _requires_frozen(fxn):
603 """Decorator to verify the named module is frozen."""
Brett Cannonf522aea2012-01-16 11:46:22 -0500604 def _requires_frozen_wrapper(self, fullname):
Brett Cannon6f44d662012-04-15 16:08:47 -0400605 if not _imp.is_frozen(fullname):
Florent Xicluna79d79a02012-07-07 13:16:44 +0200606 raise ImportError("{} is not a frozen module".format(fullname),
Brett Cannonbbb66802012-04-12 21:09:01 -0400607 name=fullname)
Brett Cannon8d110132009-03-15 02:20:16 +0000608 return fxn(self, fullname)
Brett Cannonf522aea2012-01-16 11:46:22 -0500609 _wrap(_requires_frozen_wrapper, fxn)
610 return _requires_frozen_wrapper
Brett Cannon8d110132009-03-15 02:20:16 +0000611
612
Brett Cannonf410ce82012-08-10 17:41:23 -0400613def _find_module_shim(self, fullname):
614 """Try to find a loader for the specified module by delegating to
615 self.find_loader()."""
616 # Call find_loader(). If it returns a string (indicating this
617 # is a namespace package portion), generate a warning and
618 # return None.
619 loader, portions = self.find_loader(fullname)
620 if loader is None and len(portions):
621 msg = "Not importing directory {}: missing __init__"
622 _warnings.warn(msg.format(portions[0]), ImportWarning)
623 return loader
624
625
626
627
Brett Cannone9103d22009-03-12 22:37:06 +0000628# Loaders #####################################################################
Brett Cannonce43ddf2009-03-12 22:28:55 +0000629
Brett Cannon5abdc932009-01-22 22:43:07 +0000630class BuiltinImporter:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000631
Brett Cannon7aa21f72009-03-15 00:53:05 +0000632 """Meta path import for built-in modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000633
Brett Cannon7aa21f72009-03-15 00:53:05 +0000634 All methods are either class or static methods to avoid the need to
635 instantiate the class.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000636
637 """
638
Brett Cannon5abdc932009-01-22 22:43:07 +0000639 @classmethod
Eric V. Smith984b11f2012-05-24 20:21:04 -0400640 def module_repr(cls, module):
641 return "<module '{}' (built-in)>".format(module.__name__)
642
643 @classmethod
Brett Cannon5abdc932009-01-22 22:43:07 +0000644 def find_module(cls, fullname, path=None):
Brett Cannon7aa21f72009-03-15 00:53:05 +0000645 """Find the built-in module.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000646
647 If 'path' is ever specified then the search is considered a failure.
648
649 """
650 if path is not None:
651 return None
Brett Cannon6f44d662012-04-15 16:08:47 -0400652 return cls if _imp.is_builtin(fullname) else None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000653
Brett Cannon78246b62009-01-25 04:56:30 +0000654 @classmethod
Brett Cannon435aad82009-03-04 16:07:00 +0000655 @set_package
Brett Cannon2cf03a82009-03-10 05:17:37 +0000656 @set_loader
Brett Cannona113ac52009-03-15 01:41:33 +0000657 @_requires_builtin
Brett Cannon78246b62009-01-25 04:56:30 +0000658 def load_module(cls, fullname):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000659 """Load a built-in module."""
Brett Cannond2e7b332009-02-17 02:45:03 +0000660 is_reload = fullname in sys.modules
661 try:
Nick Coghlan42c07662012-07-31 21:14:18 +1000662 return _call_with_frames_removed(_imp.init_builtin, fullname)
Brett Cannond2e7b332009-02-17 02:45:03 +0000663 except:
664 if not is_reload and fullname in sys.modules:
665 del sys.modules[fullname]
666 raise
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000667
Brett Cannona113ac52009-03-15 01:41:33 +0000668 @classmethod
669 @_requires_builtin
670 def get_code(cls, fullname):
671 """Return None as built-in modules do not have code objects."""
672 return None
673
674 @classmethod
675 @_requires_builtin
676 def get_source(cls, fullname):
677 """Return None as built-in modules do not have source code."""
678 return None
679
680 @classmethod
681 @_requires_builtin
682 def is_package(cls, fullname):
Florent Xicluna79d79a02012-07-07 13:16:44 +0200683 """Return False as built-in modules are never packages."""
Brett Cannona113ac52009-03-15 01:41:33 +0000684 return False
685
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000686
Brett Cannon5abdc932009-01-22 22:43:07 +0000687class FrozenImporter:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000688
Brett Cannon7aa21f72009-03-15 00:53:05 +0000689 """Meta path import for frozen modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000690
Brett Cannon7aa21f72009-03-15 00:53:05 +0000691 All methods are either class or static methods to avoid the need to
692 instantiate the class.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000693
Brett Cannon5abdc932009-01-22 22:43:07 +0000694 """
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000695
Brett Cannon5abdc932009-01-22 22:43:07 +0000696 @classmethod
Eric V. Smith984b11f2012-05-24 20:21:04 -0400697 def module_repr(cls, m):
698 return "<module '{}' (frozen)>".format(m.__name__)
699
700 @classmethod
Brett Cannon5abdc932009-01-22 22:43:07 +0000701 def find_module(cls, fullname, path=None):
702 """Find a frozen module."""
Brett Cannon6f44d662012-04-15 16:08:47 -0400703 return cls if _imp.is_frozen(fullname) else None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000704
Brett Cannon5abdc932009-01-22 22:43:07 +0000705 @classmethod
Brett Cannon435aad82009-03-04 16:07:00 +0000706 @set_package
Brett Cannon2cf03a82009-03-10 05:17:37 +0000707 @set_loader
Brett Cannon8d110132009-03-15 02:20:16 +0000708 @_requires_frozen
Brett Cannon5abdc932009-01-22 22:43:07 +0000709 def load_module(cls, fullname):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000710 """Load a frozen module."""
Brett Cannond2e7b332009-02-17 02:45:03 +0000711 is_reload = fullname in sys.modules
712 try:
Nick Coghlan42c07662012-07-31 21:14:18 +1000713 m = _call_with_frames_removed(_imp.init_frozen, fullname)
Eric V. Smith984b11f2012-05-24 20:21:04 -0400714 # Let our own module_repr() method produce a suitable repr.
715 del m.__file__
716 return m
Brett Cannond2e7b332009-02-17 02:45:03 +0000717 except:
718 if not is_reload and fullname in sys.modules:
719 del sys.modules[fullname]
720 raise
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000721
Brett Cannon8d110132009-03-15 02:20:16 +0000722 @classmethod
723 @_requires_frozen
724 def get_code(cls, fullname):
725 """Return the code object for the frozen module."""
Brett Cannon6f44d662012-04-15 16:08:47 -0400726 return _imp.get_frozen_object(fullname)
Brett Cannon8d110132009-03-15 02:20:16 +0000727
728 @classmethod
729 @_requires_frozen
730 def get_source(cls, fullname):
731 """Return None as frozen modules do not have source code."""
732 return None
733
734 @classmethod
735 @_requires_frozen
736 def is_package(cls, fullname):
Philip Jenvey688a5512012-08-10 16:21:35 -0700737 """Return True if the frozen module is a package."""
Brett Cannon6f44d662012-04-15 16:08:47 -0400738 return _imp.is_frozen_package(fullname)
Brett Cannon8d110132009-03-15 02:20:16 +0000739
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000740
Nick Coghlanff794862012-08-02 21:45:24 +1000741class WindowsRegistryFinder:
Martin v. Löwise3010a82012-07-28 21:33:05 +0200742
Nick Coghlanff794862012-08-02 21:45:24 +1000743 """Meta path finder for modules declared in the Windows registry.
Martin v. Löwise3010a82012-07-28 21:33:05 +0200744 """
745
746 REGISTRY_KEY = (
747 "Software\\Python\\PythonCore\\{sys_version}"
748 "\\Modules\\{fullname}")
749 REGISTRY_KEY_DEBUG = (
750 "Software\\Python\\PythonCore\\{sys_version}"
751 "\\Modules\\{fullname}\\Debug")
752 DEBUG_BUILD = False # Changed in _setup()
753
754 @classmethod
755 def _open_registry(cls, key):
756 try:
757 return _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, key)
758 except WindowsError:
759 return _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key)
760
761 @classmethod
762 def _search_registry(cls, fullname):
763 if cls.DEBUG_BUILD:
764 registry_key = cls.REGISTRY_KEY_DEBUG
765 else:
766 registry_key = cls.REGISTRY_KEY
767 key = registry_key.format(fullname=fullname,
768 sys_version=sys.version[:3])
769 try:
770 with cls._open_registry(key) as hkey:
771 filepath = _winreg.QueryValue(hkey, "")
772 except WindowsError:
773 return None
774 return filepath
775
776 @classmethod
777 def find_module(cls, fullname, path=None):
778 """Find module named in the registry."""
779 filepath = cls._search_registry(fullname)
780 if filepath is None:
781 return None
782 try:
783 _os.stat(filepath)
784 except OSError:
785 return None
786 for loader, suffixes, _ in _get_supported_file_loaders():
787 if filepath.endswith(tuple(suffixes)):
788 return loader(fullname, filepath)
789
790
Brett Cannon61b14252010-07-03 21:48:25 +0000791class _LoaderBasics:
792
793 """Base class of common code needed by both SourceLoader and
Brett Cannon938d44d2012-04-22 19:58:33 -0400794 SourcelessFileLoader."""
Brett Cannon61b14252010-07-03 21:48:25 +0000795
796 def is_package(self, fullname):
797 """Concrete implementation of InspectLoader.is_package by checking if
798 the path returned by get_filename has a filename of '__init__.py'."""
Brett Cannoned672d62012-04-20 21:19:53 -0400799 filename = _path_split(self.get_filename(fullname))[1]
Brett Cannonea0b8232012-06-15 20:00:53 -0400800 filename_base = filename.rsplit('.', 1)[0]
801 tail_name = fullname.rpartition('.')[2]
802 return filename_base == '__init__' and tail_name != '__init__'
Brett Cannon61b14252010-07-03 21:48:25 +0000803
Brett Cannonbbb66802012-04-12 21:09:01 -0400804 def _bytes_from_bytecode(self, fullname, data, bytecode_path, source_stats):
Brett Cannon61b14252010-07-03 21:48:25 +0000805 """Return the marshalled bytes from bytecode, verifying the magic
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100806 number, timestamp and source size along the way.
Brett Cannon61b14252010-07-03 21:48:25 +0000807
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100808 If source_stats is None then skip the timestamp check.
Brett Cannon61b14252010-07-03 21:48:25 +0000809
810 """
811 magic = data[:4]
812 raw_timestamp = data[4:8]
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100813 raw_size = data[8:12]
Brett Cannon77b2abd2012-07-09 16:09:00 -0400814 if magic != _MAGIC_BYTES:
Brett Cannon24117a72012-04-20 18:04:03 -0400815 msg = 'bad magic number in {!r}: {!r}'.format(fullname, magic)
816 raise ImportError(msg, name=fullname, path=bytecode_path)
Brett Cannon61b14252010-07-03 21:48:25 +0000817 elif len(raw_timestamp) != 4:
Brett Cannonfd074152012-04-14 14:10:13 -0400818 message = 'bad timestamp in {}'.format(fullname)
Brett Cannon17098a52012-05-04 13:52:49 -0400819 _verbose_message(message)
Brett Cannonfd074152012-04-14 14:10:13 -0400820 raise EOFError(message)
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100821 elif len(raw_size) != 4:
Brett Cannonfd074152012-04-14 14:10:13 -0400822 message = 'bad size in {}'.format(fullname)
Brett Cannon17098a52012-05-04 13:52:49 -0400823 _verbose_message(message)
Brett Cannonfd074152012-04-14 14:10:13 -0400824 raise EOFError(message)
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100825 if source_stats is not None:
826 try:
827 source_mtime = int(source_stats['mtime'])
828 except KeyError:
829 pass
830 else:
Brett Cannonc264e3e2012-01-25 18:58:03 -0500831 if _r_long(raw_timestamp) != source_mtime:
Brett Cannonfd074152012-04-14 14:10:13 -0400832 message = 'bytecode is stale for {}'.format(fullname)
Brett Cannon17098a52012-05-04 13:52:49 -0400833 _verbose_message(message)
Brett Cannonfd074152012-04-14 14:10:13 -0400834 raise ImportError(message, name=fullname,
835 path=bytecode_path)
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100836 try:
837 source_size = source_stats['size'] & 0xFFFFFFFF
838 except KeyError:
839 pass
840 else:
Brett Cannonc264e3e2012-01-25 18:58:03 -0500841 if _r_long(raw_size) != source_size:
Philip Jenvey4b42ff62012-02-24 21:48:17 -0800842 raise ImportError(
Brett Cannonbbb66802012-04-12 21:09:01 -0400843 "bytecode is stale for {}".format(fullname),
844 name=fullname, path=bytecode_path)
Brett Cannon61b14252010-07-03 21:48:25 +0000845 # Can't return the code object as errors from marshal loading need to
846 # propagate even when source is available.
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100847 return data[12:]
Brett Cannon61b14252010-07-03 21:48:25 +0000848
849 @module_for_loader
850 def _load_module(self, module, *, sourceless=False):
851 """Helper for load_module able to handle either source or sourceless
852 loading."""
853 name = module.__name__
854 code_object = self.get_code(name)
855 module.__file__ = self.get_filename(name)
856 if not sourceless:
Brett Cannon19a2f592012-07-09 13:58:07 -0400857 try:
858 module.__cached__ = cache_from_source(module.__file__)
859 except NotImplementedError:
860 module.__cached__ = module.__file__
Brett Cannon61b14252010-07-03 21:48:25 +0000861 else:
862 module.__cached__ = module.__file__
863 module.__package__ = name
864 if self.is_package(name):
Brett Cannoned672d62012-04-20 21:19:53 -0400865 module.__path__ = [_path_split(module.__file__)[0]]
Brett Cannon61b14252010-07-03 21:48:25 +0000866 else:
867 module.__package__ = module.__package__.rpartition('.')[0]
868 module.__loader__ = self
Nick Coghlan42c07662012-07-31 21:14:18 +1000869 _call_with_frames_removed(exec, code_object, module.__dict__)
Brett Cannon61b14252010-07-03 21:48:25 +0000870 return module
871
872
873class SourceLoader(_LoaderBasics):
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000874
Raymond Hettingercd92f372011-01-13 02:31:25 +0000875 def path_mtime(self, path):
Raymond Hettingerd958ea72011-01-13 19:08:04 +0000876 """Optional method that returns the modification time (an int) for the
877 specified path, where path is a str.
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000878 """
879 raise NotImplementedError
880
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100881 def path_stats(self, path):
882 """Optional method returning a metadata dict for the specified path
883 to by the path (str).
884 Possible keys:
885 - 'mtime' (mandatory) is the numeric timestamp of last source
886 code modification;
887 - 'size' (optional) is the size in bytes of the source code.
888
889 Implementing this method allows the loader to read bytecode files.
890 """
891 return {'mtime': self.path_mtime(path)}
892
Nick Coghlana5087702012-08-24 18:32:40 +1000893 def _cache_bytecode(self, source_path, cache_path, data):
894 """Optional method which writes data (bytes) to a file path (a str).
895
896 Implementing this method allows for the writing of bytecode files.
897
898 The source path is needed in order to correctly transfer permissions
899 """
900 # For backwards compatibility, we delegate to set_data()
901 return self.set_data(cache_path, data)
902
Raymond Hettingercd92f372011-01-13 02:31:25 +0000903 def set_data(self, path, data):
Raymond Hettingerd958ea72011-01-13 19:08:04 +0000904 """Optional method which writes data (bytes) to a file path (a str).
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000905
906 Implementing this method allows for the writing of bytecode files.
907
908 """
909 raise NotImplementedError
910
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000911
912 def get_source(self, fullname):
913 """Concrete implementation of InspectLoader.get_source."""
914 import tokenize
915 path = self.get_filename(fullname)
916 try:
917 source_bytes = self.get_data(path)
Nick Coghlan2824cb52012-07-15 22:12:14 +1000918 except IOError as exc:
Brett Cannonbbb66802012-04-12 21:09:01 -0400919 raise ImportError("source not available through get_data()",
Nick Coghlan2824cb52012-07-15 22:12:14 +1000920 name=fullname) from exc
921 readsource = _io.BytesIO(source_bytes).readline
922 try:
923 encoding = tokenize.detect_encoding(readsource)
924 except SyntaxError as exc:
925 raise ImportError("Failed to detect encoding",
926 name=fullname) from exc
Brett Cannon418182e2010-07-03 22:32:41 +0000927 newline_decoder = _io.IncrementalNewlineDecoder(None, True)
Nick Coghlan2824cb52012-07-15 22:12:14 +1000928 try:
929 return newline_decoder.decode(source_bytes.decode(encoding[0]))
930 except UnicodeDecodeError as exc:
931 raise ImportError("Failed to decode source file",
932 name=fullname) from exc
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000933
934 def get_code(self, fullname):
935 """Concrete implementation of InspectLoader.get_code.
936
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100937 Reading of bytecode requires path_stats to be implemented. To write
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000938 bytecode, set_data must also be implemented.
939
940 """
941 source_path = self.get_filename(fullname)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000942 source_mtime = None
Brett Cannon19a2f592012-07-09 13:58:07 -0400943 try:
944 bytecode_path = cache_from_source(source_path)
945 except NotImplementedError:
946 bytecode_path = None
947 else:
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000948 try:
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100949 st = self.path_stats(source_path)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000950 except NotImplementedError:
951 pass
952 else:
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100953 source_mtime = int(st['mtime'])
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000954 try:
955 data = self.get_data(bytecode_path)
956 except IOError:
957 pass
958 else:
Brett Cannon61b14252010-07-03 21:48:25 +0000959 try:
960 bytes_data = self._bytes_from_bytecode(fullname, data,
Brett Cannonbbb66802012-04-12 21:09:01 -0400961 bytecode_path,
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100962 st)
Brett Cannon61b14252010-07-03 21:48:25 +0000963 except (ImportError, EOFError):
964 pass
965 else:
Brett Cannon17098a52012-05-04 13:52:49 -0400966 _verbose_message('{} matches {}', bytecode_path,
Brett Cannonfd074152012-04-14 14:10:13 -0400967 source_path)
Brett Cannon61b14252010-07-03 21:48:25 +0000968 found = marshal.loads(bytes_data)
Brett Cannon17098a52012-05-04 13:52:49 -0400969 if isinstance(found, _code_type):
Brett Cannon6f44d662012-04-15 16:08:47 -0400970 _imp._fix_co_filename(found, source_path)
Brett Cannon17098a52012-05-04 13:52:49 -0400971 _verbose_message('code object from {}',
Brett Cannonfd074152012-04-14 14:10:13 -0400972 bytecode_path)
Brett Cannon61b14252010-07-03 21:48:25 +0000973 return found
974 else:
975 msg = "Non-code object in {}"
Brett Cannonbbb66802012-04-12 21:09:01 -0400976 raise ImportError(msg.format(bytecode_path),
977 name=fullname, path=bytecode_path)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000978 source_bytes = self.get_data(source_path)
Nick Coghlan42c07662012-07-31 21:14:18 +1000979 code_object = _call_with_frames_removed(compile,
980 source_bytes, source_path, 'exec',
981 dont_inherit=True)
Brett Cannon17098a52012-05-04 13:52:49 -0400982 _verbose_message('code object from {}', source_path)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000983 if (not sys.dont_write_bytecode and bytecode_path is not None and
Philip Jenvey4b42ff62012-02-24 21:48:17 -0800984 source_mtime is not None):
Brett Cannon77b2abd2012-07-09 16:09:00 -0400985 data = bytearray(_MAGIC_BYTES)
Brett Cannonc264e3e2012-01-25 18:58:03 -0500986 data.extend(_w_long(source_mtime))
987 data.extend(_w_long(len(source_bytes)))
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000988 data.extend(marshal.dumps(code_object))
989 try:
Nick Coghlana5087702012-08-24 18:32:40 +1000990 self._cache_bytecode(source_path, bytecode_path, data)
Brett Cannon17098a52012-05-04 13:52:49 -0400991 _verbose_message('wrote {!r}', bytecode_path)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000992 except NotImplementedError:
993 pass
994 return code_object
995
Brett Cannon61b14252010-07-03 21:48:25 +0000996 def load_module(self, fullname):
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000997 """Concrete implementation of Loader.load_module.
998
999 Requires ExecutionLoader.get_filename and ResourceLoader.get_data to be
1000 implemented to load source code. Use of bytecode is dictated by whether
1001 get_code uses/writes bytecode.
1002
1003 """
Brett Cannon61b14252010-07-03 21:48:25 +00001004 return self._load_module(fullname)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001005
1006
Brett Cannon938d44d2012-04-22 19:58:33 -04001007class FileLoader:
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001008
Brett Cannon61b14252010-07-03 21:48:25 +00001009 """Base file loader class which implements the loader protocol methods that
1010 require file system usage."""
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001011
1012 def __init__(self, fullname, path):
Brett Cannon61b14252010-07-03 21:48:25 +00001013 """Cache the module name and the path to the file found by the
1014 finder."""
Brett Cannon938d44d2012-04-22 19:58:33 -04001015 self.name = fullname
1016 self.path = path
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001017
1018 @_check_name
Brett Cannonc0499522012-05-11 14:48:41 -04001019 def load_module(self, fullname):
1020 """Load a module from a file."""
Nick Coghlan5c6eba32012-05-27 17:49:58 +10001021 # Issue #14857: Avoid the zero-argument form so the implementation
1022 # of that form can be updated without breaking the frozen module
1023 return super(FileLoader, self).load_module(fullname)
Brett Cannonc0499522012-05-11 14:48:41 -04001024
1025 @_check_name
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001026 def get_filename(self, fullname):
1027 """Return the path to the source file as found by the finder."""
Brett Cannon938d44d2012-04-22 19:58:33 -04001028 return self.path
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001029
Brett Cannon61b14252010-07-03 21:48:25 +00001030 def get_data(self, path):
1031 """Return the data from path as raw bytes."""
Florent Xicluna764d6122010-09-03 19:55:26 +00001032 with _io.FileIO(path, 'r') as file:
Brett Cannon61b14252010-07-03 21:48:25 +00001033 return file.read()
1034
1035
Brett Cannon938d44d2012-04-22 19:58:33 -04001036class SourceFileLoader(FileLoader, SourceLoader):
Brett Cannon61b14252010-07-03 21:48:25 +00001037
1038 """Concrete implementation of SourceLoader using the file system."""
1039
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001040 def path_stats(self, path):
Philip Jenvey688a5512012-08-10 16:21:35 -07001041 """Return the metadata for the path."""
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001042 st = _os.stat(path)
1043 return {'mtime': st.st_mtime, 'size': st.st_size}
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001044
Nick Coghlana5087702012-08-24 18:32:40 +10001045 def _cache_bytecode(self, source_path, bytecode_path, data):
1046 # Adapt between the two APIs
Brett Cannonba0a3ed2012-08-24 13:48:39 -04001047 try:
1048 mode = _os.stat(source_path).st_mode
1049 except OSError:
1050 mode = 0o666
1051 return self.set_data(bytecode_path, data, _mode=mode)
Nick Coghlana5087702012-08-24 18:32:40 +10001052
Brett Cannonba0a3ed2012-08-24 13:48:39 -04001053 def set_data(self, path, data, *, _mode=0o666):
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001054 """Write bytes data to a file."""
Brett Cannoned672d62012-04-20 21:19:53 -04001055 parent, filename = _path_split(path)
Brett Cannonee6d6472010-08-22 22:19:11 +00001056 path_parts = []
1057 # Figure out what directories are missing.
1058 while parent and not _path_isdir(parent):
Brett Cannoned672d62012-04-20 21:19:53 -04001059 parent, part = _path_split(parent)
Brett Cannonee6d6472010-08-22 22:19:11 +00001060 path_parts.append(part)
1061 # Create needed directories.
1062 for part in reversed(path_parts):
1063 parent = _path_join(parent, part)
1064 try:
1065 _os.mkdir(parent)
Florent Xicluna68f71a32011-10-28 16:06:23 +02001066 except FileExistsError:
Brett Cannonee6d6472010-08-22 22:19:11 +00001067 # Probably another Python process already created the dir.
Florent Xicluna68f71a32011-10-28 16:06:23 +02001068 continue
1069 except PermissionError:
Brett Cannonee6d6472010-08-22 22:19:11 +00001070 # If can't get proper access, then just forget about writing
1071 # the data.
Florent Xicluna68f71a32011-10-28 16:06:23 +02001072 return
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001073 try:
Brett Cannonba0a3ed2012-08-24 13:48:39 -04001074 _write_atomic(path, data, _mode)
Brett Cannon17098a52012-05-04 13:52:49 -04001075 _verbose_message('created {!r}', path)
Charles-François Natali6db1c402012-02-22 21:03:09 +01001076 except (PermissionError, FileExistsError):
1077 # Don't worry if you can't write bytecode or someone is writing
1078 # it at the same time.
Antoine Pitroudaaaec92011-10-19 23:28:40 +02001079 pass
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001080
1081
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +02001082class SourcelessFileLoader(FileLoader, _LoaderBasics):
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001083
Brett Cannon61b14252010-07-03 21:48:25 +00001084 """Loader which handles sourceless file imports."""
Brett Cannon91cf8822009-02-21 05:41:15 +00001085
Brett Cannon61b14252010-07-03 21:48:25 +00001086 def load_module(self, fullname):
1087 return self._load_module(fullname, sourceless=True)
Brett Cannon69194272009-07-20 04:23:48 +00001088
Brett Cannon91cf8822009-02-21 05:41:15 +00001089 def get_code(self, fullname):
Brett Cannon61b14252010-07-03 21:48:25 +00001090 path = self.get_filename(fullname)
1091 data = self.get_data(path)
Brett Cannonbbb66802012-04-12 21:09:01 -04001092 bytes_data = self._bytes_from_bytecode(fullname, data, path, None)
Brett Cannon61b14252010-07-03 21:48:25 +00001093 found = marshal.loads(bytes_data)
Brett Cannon17098a52012-05-04 13:52:49 -04001094 if isinstance(found, _code_type):
1095 _verbose_message('code object from {!r}', path)
Brett Cannon61b14252010-07-03 21:48:25 +00001096 return found
1097 else:
Brett Cannonbbb66802012-04-12 21:09:01 -04001098 raise ImportError("Non-code object in {}".format(path),
1099 name=fullname, path=path)
Brett Cannon91cf8822009-02-21 05:41:15 +00001100
Brett Cannond43b30b2009-03-10 03:29:23 +00001101 def get_source(self, fullname):
Brett Cannon61b14252010-07-03 21:48:25 +00001102 """Return None as there is no source code."""
1103 return None
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001104
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001105
Brett Cannonac9f2f32012-08-10 13:47:54 -04001106# Filled in by _setup().
1107EXTENSION_SUFFIXES = []
1108
1109
Brett Cannon938d44d2012-04-22 19:58:33 -04001110class ExtensionFileLoader:
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001111
Brett Cannone9103d22009-03-12 22:37:06 +00001112 """Loader for extension modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001113
Brett Cannone9103d22009-03-12 22:37:06 +00001114 The constructor is designed to work with FileFinder.
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001115
1116 """
1117
Brett Cannon61b14252010-07-03 21:48:25 +00001118 def __init__(self, name, path):
Brett Cannon938d44d2012-04-22 19:58:33 -04001119 self.name = name
1120 self.path = path
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001121
Brett Cannone9103d22009-03-12 22:37:06 +00001122 @_check_name
1123 @set_package
1124 @set_loader
1125 def load_module(self, fullname):
1126 """Load an extension module."""
1127 is_reload = fullname in sys.modules
1128 try:
Nick Coghlan42c07662012-07-31 21:14:18 +10001129 module = _call_with_frames_removed(_imp.load_dynamic,
1130 fullname, self.path)
Brett Cannon17098a52012-05-04 13:52:49 -04001131 _verbose_message('extension module loaded from {!r}', self.path)
Brett Cannonb428f472012-08-11 19:43:29 -04001132 if self.is_package(fullname) and not hasattr(module, '__path__'):
Brett Cannonac9f2f32012-08-10 13:47:54 -04001133 module.__path__ = [_path_split(self.path)[0]]
Brett Cannonfd074152012-04-14 14:10:13 -04001134 return module
Brett Cannone9103d22009-03-12 22:37:06 +00001135 except:
1136 if not is_reload and fullname in sys.modules:
1137 del sys.modules[fullname]
1138 raise
1139
Brett Cannone9103d22009-03-12 22:37:06 +00001140 def is_package(self, fullname):
Philip Jenvey688a5512012-08-10 16:21:35 -07001141 """Return True if the extension module is a package."""
Brett Cannonac9f2f32012-08-10 13:47:54 -04001142 file_name = _path_split(self.path)[1]
Philip Jenvey731d48a2012-08-10 11:53:54 -07001143 return any(file_name == '__init__' + suffix
1144 for suffix in EXTENSION_SUFFIXES)
Brett Cannone9103d22009-03-12 22:37:06 +00001145
Brett Cannone9103d22009-03-12 22:37:06 +00001146 def get_code(self, fullname):
1147 """Return None as an extension module cannot create a code object."""
1148 return None
1149
Brett Cannone9103d22009-03-12 22:37:06 +00001150 def get_source(self, fullname):
1151 """Return None as extension modules have no source code."""
1152 return None
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001153
1154
Eric V. Smith984b11f2012-05-24 20:21:04 -04001155class _NamespacePath:
1156 """Represents a namespace package's path. It uses the module name
1157 to find its parent module, and from there it looks up the parent's
1158 __path__. When this changes, the module's own path is recomputed,
1159 using path_finder. For top-leve modules, the parent module's path
1160 is sys.path."""
1161
1162 def __init__(self, name, path, path_finder):
1163 self._name = name
1164 self._path = path
1165 self._last_parent_path = tuple(self._get_parent_path())
1166 self._path_finder = path_finder
1167
1168 def _find_parent_path_names(self):
1169 """Returns a tuple of (parent-module-name, parent-path-attr-name)"""
1170 parent, dot, me = self._name.rpartition('.')
1171 if dot == '':
1172 # This is a top-level module. sys.path contains the parent path.
1173 return 'sys', 'path'
1174 # Not a top-level module. parent-module.__path__ contains the
1175 # parent path.
1176 return parent, '__path__'
1177
1178 def _get_parent_path(self):
1179 parent_module_name, path_attr_name = self._find_parent_path_names()
1180 return getattr(sys.modules[parent_module_name], path_attr_name)
1181
1182 def _recalculate(self):
1183 # If the parent's path has changed, recalculate _path
1184 parent_path = tuple(self._get_parent_path()) # Make a copy
1185 if parent_path != self._last_parent_path:
1186 loader, new_path = self._path_finder(self._name, parent_path)
1187 # Note that no changes are made if a loader is returned, but we
1188 # do remember the new parent path
1189 if loader is None:
1190 self._path = new_path
1191 self._last_parent_path = parent_path # Save the copy
1192 return self._path
1193
1194 def __iter__(self):
1195 return iter(self._recalculate())
1196
1197 def __len__(self):
1198 return len(self._recalculate())
1199
1200 def __repr__(self):
Florent Xicluna79d79a02012-07-07 13:16:44 +02001201 return "_NamespacePath({!r})".format(self._path)
Eric V. Smith984b11f2012-05-24 20:21:04 -04001202
1203 def __contains__(self, item):
1204 return item in self._recalculate()
1205
1206 def append(self, item):
1207 self._path.append(item)
1208
1209
1210class NamespaceLoader:
1211 def __init__(self, name, path, path_finder):
1212 self._path = _NamespacePath(name, path, path_finder)
1213
1214 @classmethod
1215 def module_repr(cls, module):
1216 return "<module '{}' (namespace)>".format(module.__name__)
1217
Eric V. Smith984b11f2012-05-24 20:21:04 -04001218 @module_for_loader
1219 def load_module(self, module):
1220 """Load a namespace module."""
1221 _verbose_message('namespace module loaded with path {!r}', self._path)
1222 module.__path__ = self._path
1223 return module
1224
1225
Brett Cannone9103d22009-03-12 22:37:06 +00001226# Finders #####################################################################
Brett Cannon4afab6b2009-02-21 03:31:35 +00001227
Brett Cannonf7e5a8c2009-02-05 02:52:18 +00001228class PathFinder:
Brett Cannon1d376682009-02-02 19:19:36 +00001229
Nick Coghlan49417742012-08-02 23:03:58 +10001230 """Meta path finder for sys.path and package __path__ attributes."""
Brett Cannon1d376682009-02-02 19:19:36 +00001231
Brett Cannonf7e5a8c2009-02-05 02:52:18 +00001232 @classmethod
Brett Cannonf4dc9202012-08-10 12:21:12 -04001233 def invalidate_caches(cls):
1234 """Call the invalidate_caches() method on all path entry finders
1235 stored in sys.path_importer_caches (where implemented)."""
1236 for finder in sys.path_importer_cache.values():
1237 if hasattr(finder, 'invalidate_caches'):
1238 finder.invalidate_caches()
1239
1240 @classmethod
Brett Cannone0d88a12012-04-25 20:54:04 -04001241 def _path_hooks(cls, path):
Brett Cannon32732e32009-02-15 05:48:13 +00001242 """Search sequence of hooks for a finder for 'path'.
Brett Cannon1d376682009-02-02 19:19:36 +00001243
Brett Cannon32732e32009-02-15 05:48:13 +00001244 If 'hooks' is false then use sys.path_hooks.
Brett Cannon1d376682009-02-02 19:19:36 +00001245
1246 """
Brett Cannone0d88a12012-04-25 20:54:04 -04001247 if not sys.path_hooks:
1248 _warnings.warn('sys.path_hooks is empty', ImportWarning)
1249 for hook in sys.path_hooks:
Brett Cannon1d376682009-02-02 19:19:36 +00001250 try:
1251 return hook(path)
1252 except ImportError:
1253 continue
1254 else:
Brett Cannonaa936422012-04-27 15:30:58 -04001255 return None
Brett Cannon1d376682009-02-02 19:19:36 +00001256
Brett Cannonf7e5a8c2009-02-05 02:52:18 +00001257 @classmethod
Brett Cannone0d88a12012-04-25 20:54:04 -04001258 def _path_importer_cache(cls, path):
Nick Coghlan49417742012-08-02 23:03:58 +10001259 """Get the finder for the path entry from sys.path_importer_cache.
Brett Cannon1d376682009-02-02 19:19:36 +00001260
Nick Coghlan49417742012-08-02 23:03:58 +10001261 If the path entry is not in the cache, find the appropriate finder
1262 and cache it. If no finder is available, store None.
Brett Cannon1d376682009-02-02 19:19:36 +00001263
1264 """
Brett Cannonf58d45c2012-02-16 18:12:00 -05001265 if path == '':
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001266 path = '.'
Brett Cannon1d376682009-02-02 19:19:36 +00001267 try:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +00001268 finder = sys.path_importer_cache[path]
Brett Cannon1d376682009-02-02 19:19:36 +00001269 except KeyError:
Brett Cannonf58d45c2012-02-16 18:12:00 -05001270 finder = cls._path_hooks(path)
Brett Cannon1d376682009-02-02 19:19:36 +00001271 sys.path_importer_cache[path] = finder
Brett Cannon1d376682009-02-02 19:19:36 +00001272 return finder
1273
Brett Cannonf7e5a8c2009-02-05 02:52:18 +00001274 @classmethod
Eric V. Smith984b11f2012-05-24 20:21:04 -04001275 def _get_loader(cls, fullname, path):
1276 """Find the loader or namespace_path for this module/package name."""
1277 # If this ends up being a namespace package, namespace_path is
1278 # the list of paths that will become its __path__
1279 namespace_path = []
1280 for entry in path:
1281 finder = cls._path_importer_cache(entry)
1282 if finder is not None:
1283 if hasattr(finder, 'find_loader'):
1284 loader, portions = finder.find_loader(fullname)
1285 else:
1286 loader = finder.find_module(fullname)
1287 portions = []
1288 if loader is not None:
1289 # We found a loader: return it immediately.
Brett Cannonf4dc9202012-08-10 12:21:12 -04001290 return loader, namespace_path
Eric V. Smith984b11f2012-05-24 20:21:04 -04001291 # This is possibly part of a namespace package.
1292 # Remember these path entries (if any) for when we
1293 # create a namespace package, and continue iterating
1294 # on path.
1295 namespace_path.extend(portions)
1296 else:
Brett Cannonf4dc9202012-08-10 12:21:12 -04001297 return None, namespace_path
Eric V. Smith984b11f2012-05-24 20:21:04 -04001298
1299 @classmethod
Brett Cannonf7e5a8c2009-02-05 02:52:18 +00001300 def find_module(cls, fullname, path=None):
Brett Cannon7aa21f72009-03-15 00:53:05 +00001301 """Find the module on sys.path or 'path' based on sys.path_hooks and
1302 sys.path_importer_cache."""
Brett Cannon7bd329d2012-04-17 21:41:35 -04001303 if path is None:
Brett Cannon1d376682009-02-02 19:19:36 +00001304 path = sys.path
Eric V. Smith984b11f2012-05-24 20:21:04 -04001305 loader, namespace_path = cls._get_loader(fullname, path)
1306 if loader is not None:
1307 return loader
Brett Cannon1d376682009-02-02 19:19:36 +00001308 else:
Eric V. Smith984b11f2012-05-24 20:21:04 -04001309 if namespace_path:
1310 # We found at least one namespace path. Return a
1311 # loader which can create the namespace package.
1312 return NamespaceLoader(fullname, namespace_path, cls._get_loader)
1313 else:
1314 return None
Brett Cannon1d376682009-02-02 19:19:36 +00001315
1316
Brett Cannon938d44d2012-04-22 19:58:33 -04001317class FileFinder:
Brett Cannone9103d22009-03-12 22:37:06 +00001318
Brett Cannon61b14252010-07-03 21:48:25 +00001319 """File-based finder.
Brett Cannone9103d22009-03-12 22:37:06 +00001320
Brett Cannon938d44d2012-04-22 19:58:33 -04001321 Interactions with the file system are cached for performance, being
1322 refreshed when the directory the finder is handling has been modified.
Brett Cannone9103d22009-03-12 22:37:06 +00001323
1324 """
1325
Brett Cannon61b14252010-07-03 21:48:25 +00001326 def __init__(self, path, *details):
Brett Cannon938d44d2012-04-22 19:58:33 -04001327 """Initialize with the path to search on and a variable number of
Eric V. Smith984b11f2012-05-24 20:21:04 -04001328 3-tuples containing the loader, file suffixes the loader recognizes,
1329 and a boolean of whether the loader handles packages."""
Brett Cannonac9f2f32012-08-10 13:47:54 -04001330 loaders = []
1331 for loader, suffixes in details:
1332 loaders.extend((suffix, loader) for suffix in suffixes)
1333 self._loaders = loaders
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001334 # Base (directory) path
1335 self.path = path or '.'
1336 self._path_mtime = -1
1337 self._path_cache = set()
Antoine Pitroub5c793a2012-02-20 22:06:59 +01001338 self._relaxed_path_cache = set()
Brett Cannonb46a1792012-02-27 18:15:42 -05001339
1340 def invalidate_caches(self):
1341 """Invalidate the directory mtime."""
1342 self._path_mtime = -1
Brett Cannone9103d22009-03-12 22:37:06 +00001343
Brett Cannonf410ce82012-08-10 17:41:23 -04001344 find_module = _find_module_shim
Eric V. Smith984b11f2012-05-24 20:21:04 -04001345
1346 def find_loader(self, fullname):
1347 """Try to find a loader for the specified module, or the namespace
1348 package portions. Returns (loader, list-of-portions)."""
Eric V. Smithe51a3692012-06-24 19:13:55 -04001349 is_namespace = False
Brett Cannone9103d22009-03-12 22:37:06 +00001350 tail_module = fullname.rpartition('.')[2]
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001351 try:
1352 mtime = _os.stat(self.path).st_mtime
1353 except OSError:
1354 mtime = -1
Brett Cannonb46a1792012-02-27 18:15:42 -05001355 if mtime != self._path_mtime:
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001356 self._fill_cache()
1357 self._path_mtime = mtime
Antoine Pitroub5c793a2012-02-20 22:06:59 +01001358 # tail_module keeps the original casing, for __file__ and friends
1359 if _relax_case():
1360 cache = self._relaxed_path_cache
1361 cache_module = tail_module.lower()
1362 else:
1363 cache = self._path_cache
1364 cache_module = tail_module
Brett Cannon44590e42012-04-14 18:37:07 -04001365 # Check if the module is the name of a directory (and thus a package).
Antoine Pitroub5c793a2012-02-20 22:06:59 +01001366 if cache_module in cache:
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001367 base_path = _path_join(self.path, tail_module)
1368 if _path_isdir(base_path):
Brett Cannonac9f2f32012-08-10 13:47:54 -04001369 for suffix, loader in self._loaders:
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001370 init_filename = '__init__' + suffix
1371 full_path = _path_join(base_path, init_filename)
1372 if _path_isfile(full_path):
Eric V. Smith984b11f2012-05-24 20:21:04 -04001373 return (loader(fullname, full_path), [base_path])
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001374 else:
Eric V. Smithe51a3692012-06-24 19:13:55 -04001375 # A namespace package, return the path if we don't also
1376 # find a module in the next section.
1377 is_namespace = True
Brett Cannon44590e42012-04-14 18:37:07 -04001378 # Check for a file w/ a proper suffix exists.
Brett Cannonac9f2f32012-08-10 13:47:54 -04001379 for suffix, loader in self._loaders:
Antoine Pitroub5c793a2012-02-20 22:06:59 +01001380 if cache_module + suffix in cache:
1381 full_path = _path_join(self.path, tail_module + suffix)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001382 if _path_isfile(full_path):
Eric V. Smith984b11f2012-05-24 20:21:04 -04001383 return (loader(fullname, full_path), [])
Eric V. Smithe51a3692012-06-24 19:13:55 -04001384 if is_namespace:
1385 return (None, [base_path])
Eric V. Smith984b11f2012-05-24 20:21:04 -04001386 return (None, [])
Brett Cannon61b14252010-07-03 21:48:25 +00001387
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001388 def _fill_cache(self):
1389 """Fill the cache of potential modules and packages for this directory."""
1390 path = self.path
Nick Coghlan48fec052012-08-20 13:18:15 +10001391 try:
1392 contents = _os.listdir(path)
1393 except FileNotFoundError:
1394 # Directory has been removed since last import
1395 contents = []
Antoine Pitroub5c793a2012-02-20 22:06:59 +01001396 # We store two cached versions, to handle runtime changes of the
1397 # PYTHONCASEOK environment variable.
Brett Cannon8ff6baf2012-04-20 12:53:14 -04001398 if not sys.platform.startswith('win'):
1399 self._path_cache = set(contents)
1400 else:
1401 # Windows users can import modules with case-insensitive file
1402 # suffixes (for legacy reasons). Make the suffix lowercase here
1403 # so it's done once instead of for every import. This is safe as
1404 # the specified suffixes to check against are always specified in a
1405 # case-sensitive manner.
1406 lower_suffix_contents = set()
1407 for item in contents:
1408 name, dot, suffix = item.partition('.')
1409 if dot:
1410 new_name = '{}.{}'.format(name, suffix.lower())
1411 else:
1412 new_name = name
1413 lower_suffix_contents.add(new_name)
1414 self._path_cache = lower_suffix_contents
Brett Cannon17098a52012-05-04 13:52:49 -04001415 if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
Benjamin Peterson2a481e52012-04-18 15:25:50 -04001416 self._relaxed_path_cache = set(fn.lower() for fn in contents)
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001417
Brett Cannon938d44d2012-04-22 19:58:33 -04001418 @classmethod
1419 def path_hook(cls, *loader_details):
1420 """A class method which returns a closure to use on sys.path_hook
1421 which will return an instance using the specified loaders and the path
1422 called on the closure.
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001423
Brett Cannon938d44d2012-04-22 19:58:33 -04001424 If the path called on the closure is not a directory, ImportError is
1425 raised.
Brett Cannon61b14252010-07-03 21:48:25 +00001426
Brett Cannon938d44d2012-04-22 19:58:33 -04001427 """
1428 def path_hook_for_FileFinder(path):
1429 """Path hook for importlib.machinery.FileFinder."""
1430 if not _path_isdir(path):
1431 raise ImportError("only directories are supported", path=path)
1432 return cls(path, *loader_details)
Brett Cannon61b14252010-07-03 21:48:25 +00001433
Brett Cannon938d44d2012-04-22 19:58:33 -04001434 return path_hook_for_FileFinder
Brett Cannon61b14252010-07-03 21:48:25 +00001435
Antoine Pitrou310f95b2012-06-23 02:12:56 +02001436 def __repr__(self):
1437 return "FileFinder(%r)" % (self.path,)
Brett Cannone9103d22009-03-12 22:37:06 +00001438
1439
Brett Cannonce43ddf2009-03-12 22:28:55 +00001440# Import itself ###############################################################
1441
Brett Cannone9103d22009-03-12 22:37:06 +00001442class _ImportLockContext:
1443
1444 """Context manager for the import lock."""
1445
1446 def __enter__(self):
1447 """Acquire the import lock."""
Brett Cannon6f44d662012-04-15 16:08:47 -04001448 _imp.acquire_lock()
Brett Cannone9103d22009-03-12 22:37:06 +00001449
1450 def __exit__(self, exc_type, exc_value, exc_traceback):
1451 """Release the import lock regardless of any raised exceptions."""
Brett Cannon6f44d662012-04-15 16:08:47 -04001452 _imp.release_lock()
Brett Cannone9103d22009-03-12 22:37:06 +00001453
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001454
Brett Cannon7fab6762012-02-16 13:43:41 -05001455def _resolve_name(name, package, level):
1456 """Resolve a relative module name to an absolute one."""
Philip Jenvey4b42ff62012-02-24 21:48:17 -08001457 bits = package.rsplit('.', level - 1)
Brett Cannon625cd232012-02-24 11:20:54 -05001458 if len(bits) < level:
1459 raise ValueError('attempted relative import beyond top-level package')
1460 base = bits[0]
Florent Xicluna79d79a02012-07-07 13:16:44 +02001461 return '{}.{}'.format(base, name) if name else base
Brett Cannon7fab6762012-02-16 13:43:41 -05001462
1463
1464def _find_module(name, path):
1465 """Find a module's loader."""
Brett Cannonce418b42012-04-27 14:01:58 -04001466 if not sys.meta_path:
1467 _warnings.warn('sys.meta_path is empty', ImportWarning)
1468 for finder in sys.meta_path:
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001469 with _ImportLockContext():
1470 loader = finder.find_module(name, path)
Brett Cannon7fab6762012-02-16 13:43:41 -05001471 if loader is not None:
1472 # The parent import may have already imported this module.
1473 if name not in sys.modules:
1474 return loader
1475 else:
1476 return sys.modules[name].__loader__
1477 else:
1478 return None
1479
1480
Brett Cannon7fab6762012-02-16 13:43:41 -05001481def _sanity_check(name, package, level):
1482 """Verify arguments are "sane"."""
Brett Cannon068915c2012-02-23 18:18:48 -05001483 if not isinstance(name, str):
Brett Cannon34d8e412012-02-22 18:33:05 -05001484 raise TypeError("module name must be str, not {}".format(type(name)))
1485 if level < 0:
1486 raise ValueError('level must be >= 0')
Brett Cannon7fab6762012-02-16 13:43:41 -05001487 if package:
Brett Cannon068915c2012-02-23 18:18:48 -05001488 if not isinstance(package, str):
Brett Cannonf5007782012-02-23 18:29:12 -05001489 raise TypeError("__package__ not set to a string")
Brett Cannon7fab6762012-02-16 13:43:41 -05001490 elif package not in sys.modules:
Florent Xicluna79d79a02012-07-07 13:16:44 +02001491 msg = ("Parent module {!r} not loaded, cannot perform relative "
Brett Cannon7fab6762012-02-16 13:43:41 -05001492 "import")
1493 raise SystemError(msg.format(package))
1494 if not name and level == 0:
1495 raise ValueError("Empty module name")
1496
1497
Brett Cannon34d8e412012-02-22 18:33:05 -05001498_ERR_MSG = 'No module named {!r}'
Brett Cannon7fab6762012-02-16 13:43:41 -05001499
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001500def _find_and_load_unlocked(name, import_):
Brett Cannon7fab6762012-02-16 13:43:41 -05001501 path = None
1502 parent = name.rpartition('.')[0]
1503 if parent:
1504 if parent not in sys.modules:
Nick Coghlan42c07662012-07-31 21:14:18 +10001505 _call_with_frames_removed(import_, parent)
Brett Cannon927d8742012-04-02 20:33:56 -04001506 # Crazy side-effects!
1507 if name in sys.modules:
1508 return sys.modules[name]
Brett Cannon7fab6762012-02-16 13:43:41 -05001509 # Backwards-compatibility; be nicer to skip the dict lookup.
1510 parent_module = sys.modules[parent]
1511 try:
1512 path = parent_module.__path__
1513 except AttributeError:
1514 msg = (_ERR_MSG + '; {} is not a package').format(name, parent)
Brett Cannonbbb66802012-04-12 21:09:01 -04001515 raise ImportError(msg, name=name)
Brett Cannon34d8e412012-02-22 18:33:05 -05001516 loader = _find_module(name, path)
1517 if loader is None:
Brett Cannon12c6bda2012-08-24 18:25:59 -04001518 exc = ImportError(_ERR_MSG.format(name), name=name)
1519 # TODO(brett): switch to a proper ModuleNotFound exception in Python
1520 # 3.4.
1521 exc._not_found = True
1522 raise exc
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001523 elif name not in sys.modules:
1524 # The parent import may have already imported this module.
1525 loader.load_module(name)
Brett Cannon17098a52012-05-04 13:52:49 -04001526 _verbose_message('import {!r} # {!r}', name, loader)
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001527 # Backwards-compatibility; be nicer to skip the dict lookup.
1528 module = sys.modules[name]
Brett Cannon34d8e412012-02-22 18:33:05 -05001529 if parent:
1530 # Set the module as an attribute on its parent.
1531 parent_module = sys.modules[parent]
1532 setattr(parent_module, name.rpartition('.')[2], module)
1533 # Set __package__ if the loader did not.
Florent Xicluna79d79a02012-07-07 13:16:44 +02001534 if getattr(module, '__package__', None) is None:
Brett Cannon34d8e412012-02-22 18:33:05 -05001535 try:
1536 module.__package__ = module.__name__
1537 if not hasattr(module, '__path__'):
1538 module.__package__ = module.__package__.rpartition('.')[0]
1539 except AttributeError:
1540 pass
Brett Cannonefad00d2012-04-27 17:27:14 -04001541 # Set loader if need be.
1542 if not hasattr(module, '__loader__'):
1543 try:
1544 module.__loader__ = loader
1545 except AttributeError:
1546 pass
Brett Cannon34d8e412012-02-22 18:33:05 -05001547 return module
Brett Cannon7fab6762012-02-16 13:43:41 -05001548
1549
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001550def _find_and_load(name, import_):
1551 """Find and load the module, and release the import lock."""
1552 try:
1553 lock = _get_module_lock(name)
1554 finally:
1555 _imp.release_lock()
1556 lock.acquire()
1557 try:
1558 return _find_and_load_unlocked(name, import_)
1559 finally:
1560 lock.release()
1561
1562
Brett Cannon7f9876c2009-02-06 02:47:33 +00001563def _gcd_import(name, package=None, level=0):
1564 """Import and return the module based on its name, the package the call is
1565 being made from, and the level adjustment.
1566
1567 This function represents the greatest common denominator of functionality
Eric V. Smith41698262011-03-14 10:56:33 -04001568 between import_module and __import__. This includes setting __package__ if
Brett Cannon2c318a12009-02-07 01:15:27 +00001569 the loader did not.
1570
Brett Cannon7f9876c2009-02-06 02:47:33 +00001571 """
Brett Cannon7fab6762012-02-16 13:43:41 -05001572 _sanity_check(name, package, level)
Brett Cannon7f9876c2009-02-06 02:47:33 +00001573 if level > 0:
Brett Cannon7fab6762012-02-16 13:43:41 -05001574 name = _resolve_name(name, package, level)
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001575 _imp.acquire_lock()
1576 if name not in sys.modules:
Brett Cannon34d8e412012-02-22 18:33:05 -05001577 return _find_and_load(name, _gcd_import)
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001578 module = sys.modules[name]
1579 if module is None:
1580 _imp.release_lock()
1581 message = ("import of {} halted; "
1582 "None in sys.modules".format(name))
1583 raise ImportError(message, name=name)
1584 _lock_unlock_module(name)
1585 return module
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001586
Brett Cannon4b03b682012-02-23 20:47:57 -05001587def _handle_fromlist(module, fromlist, import_):
Brett Cannon7fab6762012-02-16 13:43:41 -05001588 """Figure out what __import__ should return.
Brett Cannon2c318a12009-02-07 01:15:27 +00001589
Brett Cannon7fab6762012-02-16 13:43:41 -05001590 The import_ parameter is a callable which takes the name of module to
1591 import. It is required to decouple the function from assuming importlib's
1592 import implementation is desired.
Brett Cannon2c318a12009-02-07 01:15:27 +00001593
1594 """
Brett Cannon2c318a12009-02-07 01:15:27 +00001595 # The hell that is fromlist ...
Brett Cannon4b03b682012-02-23 20:47:57 -05001596 # If a package was imported, try to import stuff from fromlist.
1597 if hasattr(module, '__path__'):
Brett Cannon461c8132012-07-10 10:05:00 -04001598 if '*' in fromlist:
Brett Cannon4b03b682012-02-23 20:47:57 -05001599 fromlist = list(fromlist)
1600 fromlist.remove('*')
Brett Cannon461c8132012-07-10 10:05:00 -04001601 if hasattr(module, '__all__'):
1602 fromlist.extend(module.__all__)
Florent Xicluna79d79a02012-07-07 13:16:44 +02001603 for x in fromlist:
1604 if not hasattr(module, x):
Brett Cannon7385adc2012-08-17 13:21:16 -04001605 try:
1606 _call_with_frames_removed(import_,
1607 '{}.{}'.format(module.__name__, x))
Brett Cannon12c6bda2012-08-24 18:25:59 -04001608 except ImportError as exc:
Brett Cannon7385adc2012-08-17 13:21:16 -04001609 # Backwards-compatibility dictates we ignore failed
Brett Cannon12c6bda2012-08-24 18:25:59 -04001610 # imports triggered by fromlist for modules that don't
1611 # exist.
1612 # TODO(brett): In Python 3.4, have import raise
1613 # ModuleNotFound and catch that.
1614 if hasattr(exc, '_not_found') and exc._not_found:
1615 pass
1616 else:
1617 raise
Brett Cannon4b03b682012-02-23 20:47:57 -05001618 return module
Brett Cannon354c26e2012-02-08 18:50:22 -05001619
1620
Brett Cannon7fab6762012-02-16 13:43:41 -05001621def _calc___package__(globals):
1622 """Calculate what __package__ should be.
1623
1624 __package__ is not guaranteed to be defined or could be set to None
1625 to represent that its proper value is unknown.
1626
1627 """
1628 package = globals.get('__package__')
1629 if package is None:
1630 package = globals['__name__']
1631 if '__path__' not in globals:
1632 package = package.rpartition('.')[0]
1633 return package
1634
1635
Martin v. Löwise3010a82012-07-28 21:33:05 +02001636def _get_supported_file_loaders():
1637 """Returns a list of file-based module loaders.
1638
1639 Each item is a tuple (loader, suffixes, allow_packages).
1640 """
Brett Cannonac9f2f32012-08-10 13:47:54 -04001641 extensions = ExtensionFileLoader, _imp.extension_suffixes()
1642 source = SourceFileLoader, SOURCE_SUFFIXES
1643 bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES
Martin v. Löwise3010a82012-07-28 21:33:05 +02001644 return [extensions, source, bytecode]
1645
1646
Brett Cannoncb4996a2012-08-06 16:34:44 -04001647def __import__(name, globals=None, locals=None, fromlist=(), level=0):
Brett Cannon7fab6762012-02-16 13:43:41 -05001648 """Import a module.
1649
1650 The 'globals' argument is used to infer where the import is occuring from
1651 to handle relative imports. The 'locals' argument is ignored. The
1652 'fromlist' argument specifies what should exist as attributes on the module
1653 being imported (e.g. ``from module import <fromlist>``). The 'level'
1654 argument represents the package location to import from in a relative
1655 import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
1656
1657 """
Brett Cannon7fab6762012-02-16 13:43:41 -05001658 if level == 0:
1659 module = _gcd_import(name)
1660 else:
Brett Cannoncb4996a2012-08-06 16:34:44 -04001661 globals_ = globals if globals is not None else {}
1662 package = _calc___package__(globals_)
Brett Cannon7fab6762012-02-16 13:43:41 -05001663 module = _gcd_import(name, package, level)
Brett Cannon4b03b682012-02-23 20:47:57 -05001664 if not fromlist:
1665 # Return up to the first dot in 'name'. This is complicated by the fact
1666 # that 'name' may be relative.
1667 if level == 0:
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001668 return _gcd_import(name.partition('.')[0])
Brett Cannon4b03b682012-02-23 20:47:57 -05001669 elif not name:
1670 return module
1671 else:
Brett Cannon8ed677d2012-09-28 16:41:39 -04001672 # Figure out where to slice the module's name up to the first dot
1673 # in 'name'.
Brett Cannon4b03b682012-02-23 20:47:57 -05001674 cut_off = len(name) - len(name.partition('.')[0])
Brett Cannon8ed677d2012-09-28 16:41:39 -04001675 # Slice end needs to be positive to alleviate need to special-case
1676 # when ``'.' not in name``.
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001677 return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
Brett Cannon4b03b682012-02-23 20:47:57 -05001678 else:
1679 return _handle_fromlist(module, fromlist, _gcd_import)
Brett Cannon7fab6762012-02-16 13:43:41 -05001680
1681
Brett Cannon24117a72012-04-20 18:04:03 -04001682
Brett Cannon6f44d662012-04-15 16:08:47 -04001683def _setup(sys_module, _imp_module):
Brett Cannon354c26e2012-02-08 18:50:22 -05001684 """Setup importlib by importing needed built-in modules and injecting them
1685 into the global namespace.
1686
Brett Cannon6f44d662012-04-15 16:08:47 -04001687 As sys is needed for sys.modules access and _imp is needed to load built-in
Brett Cannon0568d6f2012-02-14 18:38:11 -05001688 modules, those two modules must be explicitly passed in.
Brett Cannon354c26e2012-02-08 18:50:22 -05001689
1690 """
Benjamin Petersonfeaa54f2012-09-25 11:22:59 -04001691 global _imp, sys, BYTECODE_SUFFIXES
Brett Cannon6f44d662012-04-15 16:08:47 -04001692 _imp = _imp_module
Brett Cannon354c26e2012-02-08 18:50:22 -05001693 sys = sys_module
1694
Benjamin Petersonfeaa54f2012-09-25 11:22:59 -04001695 if sys.flags.optimize:
1696 BYTECODE_SUFFIXES = OPTIMIZED_BYTECODE_SUFFIXES
1697 else:
1698 BYTECODE_SUFFIXES = DEBUG_BYTECODE_SUFFIXES
1699
Brett Cannon6f44d662012-04-15 16:08:47 -04001700 for module in (_imp, sys):
Brett Cannon354c26e2012-02-08 18:50:22 -05001701 if not hasattr(module, '__loader__'):
1702 module.__loader__ = BuiltinImporter
1703
1704 self_module = sys.modules[__name__]
1705 for builtin_name in ('_io', '_warnings', 'builtins', 'marshal'):
1706 if builtin_name not in sys.modules:
1707 builtin_module = BuiltinImporter.load_module(builtin_name)
1708 else:
1709 builtin_module = sys.modules[builtin_name]
1710 setattr(self_module, builtin_name, builtin_module)
1711
Brett Cannoned672d62012-04-20 21:19:53 -04001712 os_details = ('posix', ['/']), ('nt', ['\\', '/']), ('os2', ['\\', '/'])
1713 for builtin_os, path_separators in os_details:
Brett Cannon5c903e62012-04-22 11:45:07 -04001714 # Assumption made in _path_join()
1715 assert all(len(sep) == 1 for sep in path_separators)
Brett Cannoned672d62012-04-20 21:19:53 -04001716 path_sep = path_separators[0]
Brett Cannon354c26e2012-02-08 18:50:22 -05001717 if builtin_os in sys.modules:
1718 os_module = sys.modules[builtin_os]
1719 break
1720 else:
1721 try:
1722 os_module = BuiltinImporter.load_module(builtin_os)
1723 # TODO: rip out os2 code after 3.3 is released as per PEP 11
1724 if builtin_os == 'os2' and 'EMX GCC' in sys.version:
Brett Cannoned672d62012-04-20 21:19:53 -04001725 path_sep = path_separators[1]
Brett Cannon354c26e2012-02-08 18:50:22 -05001726 break
1727 except ImportError:
1728 continue
1729 else:
1730 raise ImportError('importlib requires posix or nt')
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001731
1732 try:
1733 thread_module = BuiltinImporter.load_module('_thread')
1734 except ImportError:
1735 # Python was built without threads
1736 thread_module = None
1737 weakref_module = BuiltinImporter.load_module('_weakref')
1738
Martin v. Löwise3010a82012-07-28 21:33:05 +02001739 if builtin_os == 'nt':
1740 winreg_module = BuiltinImporter.load_module('winreg')
1741 setattr(self_module, '_winreg', winreg_module)
1742
Brett Cannon354c26e2012-02-08 18:50:22 -05001743 setattr(self_module, '_os', os_module)
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001744 setattr(self_module, '_thread', thread_module)
1745 setattr(self_module, '_weakref', weakref_module)
Brett Cannon354c26e2012-02-08 18:50:22 -05001746 setattr(self_module, 'path_sep', path_sep)
Brett Cannoned672d62012-04-20 21:19:53 -04001747 setattr(self_module, 'path_separators', set(path_separators))
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001748 # Constants
Antoine Pitroub67075b2012-02-20 13:52:47 +01001749 setattr(self_module, '_relax_case', _make_relax_case())
Brett Cannonac9f2f32012-08-10 13:47:54 -04001750 EXTENSION_SUFFIXES.extend(_imp.extension_suffixes())
Brett Cannona64faf02012-04-21 18:52:52 -04001751 if builtin_os == 'nt':
Brett Cannoncb66eb02012-05-11 12:58:42 -04001752 SOURCE_SUFFIXES.append('.pyw')
Brett Cannonac9f2f32012-08-10 13:47:54 -04001753 if '_d.pyd' in EXTENSION_SUFFIXES:
Nick Coghlanff794862012-08-02 21:45:24 +10001754 WindowsRegistryFinder.DEBUG_BUILD = True
Brett Cannonf2e86752012-02-17 09:46:48 -05001755
Brett Cannon0568d6f2012-02-14 18:38:11 -05001756
Brett Cannon6f44d662012-04-15 16:08:47 -04001757def _install(sys_module, _imp_module):
Brett Cannonfeccc092012-05-04 16:47:54 -04001758 """Install importlib as the implementation of import."""
Brett Cannon6f44d662012-04-15 16:08:47 -04001759 _setup(sys_module, _imp_module)
Martin v. Löwise3010a82012-07-28 21:33:05 +02001760 supported_loaders = _get_supported_file_loaders()
Brett Cannonaa936422012-04-27 15:30:58 -04001761 sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)])
Martin v. Löwise3010a82012-07-28 21:33:05 +02001762 sys.meta_path.append(BuiltinImporter)
1763 sys.meta_path.append(FrozenImporter)
1764 if _os.__name__ == 'nt':
Nick Coghlanff794862012-08-02 21:45:24 +10001765 sys.meta_path.append(WindowsRegistryFinder)
Martin v. Löwise3010a82012-07-28 21:33:05 +02001766 sys.meta_path.append(PathFinder)