blob: e2ac7ceecb4bd5300056b5e4ffdad63434f41cb5 [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 """
Brett Cannonc1903892013-02-25 17:10:11 -050051 return (int(x) & 0xFFFFFFFF).to_bytes(4, 'little')
Brett Cannonc264e3e2012-01-25 18:58:03 -050052
53
54# TODO: Expose from marshal
55def _r_long(int_bytes):
56 """Convert 4 bytes in little-endian to an integer.
57
58 XXX Temporary until marshal's long function are exposed.
59
60 """
Serhiy Storchaka39e47f92013-02-25 15:40:33 +020061 return int.from_bytes(int_bytes, 'little')
Brett Cannonc264e3e2012-01-25 18:58:03 -050062
63
Brett Cannon5c903e62012-04-22 11:45:07 -040064def _path_join(*path_parts):
Brett Cannoned672d62012-04-20 21:19:53 -040065 """Replacement for os.path.join()."""
Serhiy Storchaka39e47f92013-02-25 15:40:33 +020066 return path_sep.join([part.rstrip(path_separators)
67 for part in path_parts if part])
Brett Cannoned672d62012-04-20 21:19:53 -040068
69
70def _path_split(path):
71 """Replacement for os.path.split()."""
Serhiy Storchaka39e47f92013-02-25 15:40:33 +020072 if len(path_separators) == 1:
73 front, _, tail = path.rpartition(path_sep)
74 return front, tail
Brett Cannoned672d62012-04-20 21:19:53 -040075 for x in reversed(path):
76 if x in path_separators:
Brett Cannonc1903892013-02-25 17:10:11 -050077 front, tail = path.rsplit(x, maxsplit=1)
Serhiy Storchaka39e47f92013-02-25 15:40:33 +020078 return front, tail
79 return '', path
Brett Cannon23cbd8a2009-01-18 00:24:28 +000080
81
Brett Cannon23cbd8a2009-01-18 00:24:28 +000082def _path_is_mode_type(path, mode):
83 """Test whether the path is the specified mode type."""
84 try:
85 stat_info = _os.stat(path)
86 except OSError:
87 return False
88 return (stat_info.st_mode & 0o170000) == mode
89
90
91# XXX Could also expose Modules/getpath.c:isfile()
92def _path_isfile(path):
93 """Replacement for os.path.isfile."""
94 return _path_is_mode_type(path, 0o100000)
95
96
97# XXX Could also expose Modules/getpath.c:isdir()
98def _path_isdir(path):
99 """Replacement for os.path.isdir."""
Brett Cannon61b14252010-07-03 21:48:25 +0000100 if not path:
101 path = _os.getcwd()
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000102 return _path_is_mode_type(path, 0o040000)
103
104
Nick Coghlana5087702012-08-24 18:32:40 +1000105def _write_atomic(path, data, mode=0o666):
Charles-François Natali6db1c402012-02-22 21:03:09 +0100106 """Best-effort function to write data to a path atomically.
107 Be prepared to handle a FileExistsError if concurrent writing of the
108 temporary file is attempted."""
Antoine Pitrou28e401e2011-11-15 19:15:19 +0100109 # id() is used to generate a pseudo-random filename.
110 path_tmp = '{}.{}'.format(path, id(path))
Nick Coghlana5087702012-08-24 18:32:40 +1000111 fd = _os.open(path_tmp,
112 _os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, mode & 0o666)
Antoine Pitrou28e401e2011-11-15 19:15:19 +0100113 try:
Brett Cannonba17fe22012-02-17 09:26:53 -0500114 # We first write data to a temporary file, and then use os.replace() to
115 # perform an atomic rename.
Antoine Pitrou28e401e2011-11-15 19:15:19 +0100116 with _io.FileIO(fd, 'wb') as file:
Antoine Pitrou707033a2011-10-17 19:28:44 +0200117 file.write(data)
Brett Cannonba17fe22012-02-17 09:26:53 -0500118 _os.replace(path_tmp, path)
Antoine Pitrou28e401e2011-11-15 19:15:19 +0100119 except OSError:
120 try:
121 _os.unlink(path_tmp)
122 except OSError:
123 pass
124 raise
Antoine Pitrou707033a2011-10-17 19:28:44 +0200125
126
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000127def _wrap(new, old):
Florent Xicluna79d79a02012-07-07 13:16:44 +0200128 """Simple substitute for functools.update_wrapper."""
Meador Inge96ff0842011-12-14 22:53:13 -0600129 for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
Brett Cannon8490fab2012-02-08 18:44:14 -0500130 if hasattr(old, replace):
131 setattr(new, replace, getattr(old, replace))
Brett Cannon51d8bfc2009-02-07 02:13:28 +0000132 new.__dict__.update(old.__dict__)
133
134
Brett Cannon17098a52012-05-04 13:52:49 -0400135_code_type = type(_wrap.__code__)
Brett Cannon61b14252010-07-03 21:48:25 +0000136
Brett Cannon6f44d662012-04-15 16:08:47 -0400137
Brett Cannon17098a52012-05-04 13:52:49 -0400138def new_module(name):
Brett Cannon6f44d662012-04-15 16:08:47 -0400139 """Create a new module.
140
141 The module is not entered into sys.modules.
142
143 """
Brett Cannonf19c1912012-05-04 15:46:04 -0400144 return type(_io)(name)
Brett Cannon6f44d662012-04-15 16:08:47 -0400145
146
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200147# Module-level locking ########################################################
148
149# A dict mapping module names to weakrefs of _ModuleLock instances
150_module_locks = {}
151# A dict mapping thread ids to _ModuleLock instances
152_blocking_on = {}
153
154
155class _DeadlockError(RuntimeError):
156 pass
157
158
159class _ModuleLock:
160 """A recursive lock implementation which is able to detect deadlocks
161 (e.g. thread 1 trying to take locks A then B, and thread 2 trying to
162 take locks B then A).
163 """
164
165 def __init__(self, name):
166 self.lock = _thread.allocate_lock()
167 self.wakeup = _thread.allocate_lock()
168 self.name = name
169 self.owner = None
170 self.count = 0
171 self.waiters = 0
172
173 def has_deadlock(self):
174 # Deadlock avoidance for concurrent circular imports.
175 me = _thread.get_ident()
176 tid = self.owner
177 while True:
178 lock = _blocking_on.get(tid)
179 if lock is None:
180 return False
181 tid = lock.owner
182 if tid == me:
183 return True
184
185 def acquire(self):
186 """
187 Acquire the module lock. If a potential deadlock is detected,
188 a _DeadlockError is raised.
189 Otherwise, the lock is always acquired and True is returned.
190 """
191 tid = _thread.get_ident()
192 _blocking_on[tid] = self
193 try:
194 while True:
195 with self.lock:
196 if self.count == 0 or self.owner == tid:
197 self.owner = tid
198 self.count += 1
199 return True
200 if self.has_deadlock():
201 raise _DeadlockError("deadlock detected by %r" % self)
202 if self.wakeup.acquire(False):
203 self.waiters += 1
204 # Wait for a release() call
205 self.wakeup.acquire()
206 self.wakeup.release()
207 finally:
208 del _blocking_on[tid]
209
210 def release(self):
211 tid = _thread.get_ident()
212 with self.lock:
213 if self.owner != tid:
214 raise RuntimeError("cannot release un-acquired lock")
215 assert self.count > 0
216 self.count -= 1
217 if self.count == 0:
218 self.owner = None
219 if self.waiters:
220 self.waiters -= 1
221 self.wakeup.release()
222
223 def __repr__(self):
Brett Cannon6072e0b2012-10-12 10:00:34 -0400224 return "_ModuleLock({!r}) at {}".format(self.name, id(self))
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200225
226
227class _DummyModuleLock:
228 """A simple _ModuleLock equivalent for Python builds without
229 multi-threading support."""
230
231 def __init__(self, name):
232 self.name = name
233 self.count = 0
234
235 def acquire(self):
236 self.count += 1
237 return True
238
239 def release(self):
240 if self.count == 0:
241 raise RuntimeError("cannot release un-acquired lock")
242 self.count -= 1
243
244 def __repr__(self):
Brett Cannon6072e0b2012-10-12 10:00:34 -0400245 return "_DummyModuleLock({!r}) at {}".format(self.name, id(self))
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200246
247
248# The following two functions are for consumption by Python/import.c.
249
250def _get_module_lock(name):
251 """Get or create the module lock for a given module name.
252
253 Should only be called with the import lock taken."""
254 lock = None
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200255 try:
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200256 lock = _module_locks[name]()
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200257 except KeyError:
258 pass
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200259 if lock is None:
260 if _thread is None:
261 lock = _DummyModuleLock(name)
262 else:
263 lock = _ModuleLock(name)
264 def cb(_):
265 del _module_locks[name]
266 _module_locks[name] = _weakref.ref(lock, cb)
267 return lock
268
269def _lock_unlock_module(name):
270 """Release the global import lock, and acquires then release the
271 module lock for a given module name.
272 This is used to ensure a module is completely initialized, in the
273 event it is being imported by another thread.
274
275 Should only be called with the import lock taken."""
276 lock = _get_module_lock(name)
277 _imp.release_lock()
278 try:
279 lock.acquire()
280 except _DeadlockError:
281 # Concurrent circular import, we'll accept a partially initialized
282 # module object.
283 pass
284 else:
285 lock.release()
286
Nick Coghlan42c07662012-07-31 21:14:18 +1000287# Frame stripping magic ###############################################
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200288
Nick Coghlan42c07662012-07-31 21:14:18 +1000289def _call_with_frames_removed(f, *args, **kwds):
290 """remove_importlib_frames in import.c will always remove sequences
291 of importlib frames that end with a call to this function
292
293 Use it instead of a normal call in places where including the importlib
294 frames introduces unwanted noise into the traceback (e.g. when executing
295 module code)
296 """
297 return f(*args, **kwds)
298
299
300# Finder/loader utility code ###############################################
Brett Cannonce43ddf2009-03-12 22:28:55 +0000301
Victor Stinner765531d2013-03-26 01:11:54 +0100302# Magic word to reject .pyc files generated by other Python versions.
303# It should change for each incompatible change to the bytecode.
304#
305# The value of CR and LF is incorporated so if you ever read or write
306# a .pyc file in text mode the magic number will be wrong; also, the
307# Apple MPW compiler swaps their values, botching string constants.
308#
309# The magic numbers must be spaced apart at least 2 values, as the
310# -U interpeter flag will cause MAGIC+1 being used. They have been
311# odd numbers for some time now.
312#
313# There were a variety of old schemes for setting the magic number.
314# The current working scheme is to increment the previous value by
315# 10.
316#
317# Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
318# number also includes a new "magic tag", i.e. a human readable string used
319# to represent the magic number in __pycache__ directories. When you change
320# the magic number, you must also set a new unique magic tag. Generally this
321# can be named after the Python major version of the magic number bump, but
322# it can really be anything, as long as it's different than anything else
323# that's come before. The tags are included in the following table, starting
324# with Python 3.2a0.
325#
326# Known values:
327# Python 1.5: 20121
328# Python 1.5.1: 20121
329# Python 1.5.2: 20121
330# Python 1.6: 50428
331# Python 2.0: 50823
332# Python 2.0.1: 50823
333# Python 2.1: 60202
334# Python 2.1.1: 60202
335# Python 2.1.2: 60202
336# Python 2.2: 60717
337# Python 2.3a0: 62011
338# Python 2.3a0: 62021
339# Python 2.3a0: 62011 (!)
340# Python 2.4a0: 62041
341# Python 2.4a3: 62051
342# Python 2.4b1: 62061
343# Python 2.5a0: 62071
344# Python 2.5a0: 62081 (ast-branch)
345# Python 2.5a0: 62091 (with)
346# Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
347# Python 2.5b3: 62101 (fix wrong code: for x, in ...)
348# Python 2.5b3: 62111 (fix wrong code: x += yield)
349# Python 2.5c1: 62121 (fix wrong lnotab with for loops and
350# storing constants that should have been removed)
351# Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
352# Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
353# Python 2.6a1: 62161 (WITH_CLEANUP optimization)
354# Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
355# Python 2.7a0: 62181 (optimize conditional branches:
356# introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
357# Python 2.7a0 62191 (introduce SETUP_WITH)
358# Python 2.7a0 62201 (introduce BUILD_SET)
359# Python 2.7a0 62211 (introduce MAP_ADD and SET_ADD)
360# Python 3000: 3000
361# 3010 (removed UNARY_CONVERT)
362# 3020 (added BUILD_SET)
363# 3030 (added keyword-only parameters)
364# 3040 (added signature annotations)
365# 3050 (print becomes a function)
366# 3060 (PEP 3115 metaclass syntax)
367# 3061 (string literals become unicode)
368# 3071 (PEP 3109 raise changes)
369# 3081 (PEP 3137 make __file__ and __name__ unicode)
370# 3091 (kill str8 interning)
371# 3101 (merge from 2.6a0, see 62151)
372# 3103 (__file__ points to source file)
373# Python 3.0a4: 3111 (WITH_CLEANUP optimization).
374# Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
375# Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
376# change LIST_APPEND and SET_ADD, add MAP_ADD)
377# Python 3.1a0: 3151 (optimize conditional branches:
378# introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
379# Python 3.2a0: 3160 (add SETUP_WITH)
380# tag: cpython-32
381# Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
382# tag: cpython-32
383# Python 3.2a2 3180 (add DELETE_DEREF)
384# Python 3.3a0 3190 __class__ super closure changed
385# Python 3.3a0 3200 (__qualname__ added)
386# 3210 (added size modulo 2**32 to the pyc header)
387# Python 3.3a1 3220 (changed PEP 380 implementation)
388# Python 3.3a4 3230 (revert changes to implicit __class__ closure)
389# Python 3.4a1 3250 (evaluate positional default arguments before
390# keyword-only defaults)
391#
392# MAGIC must change whenever the bytecode emitted by the compiler may no
393# longer be understood by older implementations of the eval loop (usually
394# due to the addition of new opcodes).
Brett Cannon77b2abd2012-07-09 16:09:00 -0400395
Serhiy Storchaka39e47f92013-02-25 15:40:33 +0200396_MAGIC_BYTES = (3250).to_bytes(2, 'little') + b'\r\n'
397_RAW_MAGIC_NUMBER = int.from_bytes(_MAGIC_BYTES, 'little')
Brett Cannon77b2abd2012-07-09 16:09:00 -0400398
Brett Cannon17098a52012-05-04 13:52:49 -0400399_PYCACHE = '__pycache__'
Brett Cannonea59dbf2012-04-20 21:44:46 -0400400
Brett Cannoncb66eb02012-05-11 12:58:42 -0400401SOURCE_SUFFIXES = ['.py'] # _setup() adds .pyw as needed.
Brett Cannona64faf02012-04-21 18:52:52 -0400402
Brett Cannoncb66eb02012-05-11 12:58:42 -0400403DEBUG_BYTECODE_SUFFIXES = ['.pyc']
404OPTIMIZED_BYTECODE_SUFFIXES = ['.pyo']
Brett Cannonea59dbf2012-04-20 21:44:46 -0400405
Brett Cannon17098a52012-05-04 13:52:49 -0400406def cache_from_source(path, debug_override=None):
Brett Cannonea59dbf2012-04-20 21:44:46 -0400407 """Given the path to a .py file, return the path to its .pyc/.pyo file.
408
409 The .py file does not need to exist; this simply returns the path to the
410 .pyc/.pyo file calculated as if the .py file were imported. The extension
Benjamin Petersonfeaa54f2012-09-25 11:22:59 -0400411 will be .pyc unless sys.flags.optimize is non-zero, then it will be .pyo.
Brett Cannonea59dbf2012-04-20 21:44:46 -0400412
Benjamin Peterson52c62d82012-09-26 00:25:10 -0400413 If debug_override is not None, then it must be a boolean and is used in
414 place of sys.flags.optimize.
Brett Cannonea59dbf2012-04-20 21:44:46 -0400415
Brett Cannon19a2f592012-07-09 13:58:07 -0400416 If sys.implementation.cache_tag is None then NotImplementedError is raised.
417
Brett Cannonea59dbf2012-04-20 21:44:46 -0400418 """
Benjamin Petersonfeaa54f2012-09-25 11:22:59 -0400419 debug = not sys.flags.optimize if debug_override is None else debug_override
Brett Cannoncb66eb02012-05-11 12:58:42 -0400420 if debug:
421 suffixes = DEBUG_BYTECODE_SUFFIXES
422 else:
423 suffixes = OPTIMIZED_BYTECODE_SUFFIXES
Brett Cannonea59dbf2012-04-20 21:44:46 -0400424 head, tail = _path_split(path)
425 base_filename, sep, _ = tail.partition('.')
Brett Cannon19a2f592012-07-09 13:58:07 -0400426 tag = sys.implementation.cache_tag
427 if tag is None:
428 raise NotImplementedError('sys.implementation.cache_tag is None')
429 filename = ''.join([base_filename, sep, tag, suffixes[0]])
Brett Cannon17098a52012-05-04 13:52:49 -0400430 return _path_join(head, _PYCACHE, filename)
Brett Cannonea59dbf2012-04-20 21:44:46 -0400431
432
Brett Cannona6473f92012-07-13 13:57:03 -0400433def source_from_cache(path):
434 """Given the path to a .pyc./.pyo file, return the path to its .py file.
435
436 The .pyc/.pyo file does not need to exist; this simply returns the path to
437 the .py file calculated to correspond to the .pyc/.pyo file. If path does
438 not conform to PEP 3147 format, ValueError will be raised. If
439 sys.implementation.cache_tag is None then NotImplementedError is raised.
440
441 """
442 if sys.implementation.cache_tag is None:
443 raise NotImplementedError('sys.implementation.cache_tag is None')
444 head, pycache_filename = _path_split(path)
445 head, pycache = _path_split(head)
446 if pycache != _PYCACHE:
447 raise ValueError('{} not bottom-level directory in '
448 '{!r}'.format(_PYCACHE, path))
449 if pycache_filename.count('.') != 2:
450 raise ValueError('expected only 2 dots in '
451 '{!r}'.format(pycache_filename))
452 base_filename = pycache_filename.partition('.')[0]
453 return _path_join(head, base_filename + SOURCE_SUFFIXES[0])
454
455
456def _get_sourcefile(bytecode_path):
457 """Convert a bytecode file path to a source path (if possible).
458
459 This function exists purely for backwards-compatibility for
460 PyImport_ExecCodeModuleWithFilenames() in the C API.
461
462 """
463 if len(bytecode_path) == 0:
464 return None
465 rest, _, extension = bytecode_path.rparition('.')
466 if not rest or extension.lower()[-3:-1] != '.py':
467 return bytecode_path
468
469 try:
470 source_path = source_from_cache(bytecode_path)
471 except (NotImplementedError, ValueError):
472 source_path = bytcode_path[-1:]
473
474 return source_path if _path_isfile(source_stats) else bytecode_path
475
476
Brett Cannonf8ffec02013-04-01 13:10:51 -0400477def _verbose_message(message, *args, verbosity=1):
Brett Cannonfd074152012-04-14 14:10:13 -0400478 """Print the message to stderr if -v/PYTHONVERBOSE is turned on."""
Brett Cannonf8ffec02013-04-01 13:10:51 -0400479 if sys.flags.verbose >= verbosity:
Philip Jenveyf8f31902012-04-15 12:21:32 -0700480 if not message.startswith(('#', 'import ')):
Brett Cannonfd074152012-04-14 14:10:13 -0400481 message = '# ' + message
482 print(message.format(*args), file=sys.stderr)
483
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100484
Brett Cannon435aad82009-03-04 16:07:00 +0000485def set_package(fxn):
Brett Cannon06c9d962009-02-07 01:52:25 +0000486 """Set __package__ on the returned module."""
Brett Cannonf522aea2012-01-16 11:46:22 -0500487 def set_package_wrapper(*args, **kwargs):
Brett Cannon06c9d962009-02-07 01:52:25 +0000488 module = fxn(*args, **kwargs)
Florent Xicluna79d79a02012-07-07 13:16:44 +0200489 if getattr(module, '__package__', None) is None:
Brett Cannon06c9d962009-02-07 01:52:25 +0000490 module.__package__ = module.__name__
491 if not hasattr(module, '__path__'):
492 module.__package__ = module.__package__.rpartition('.')[0]
493 return module
Brett Cannonf522aea2012-01-16 11:46:22 -0500494 _wrap(set_package_wrapper, fxn)
495 return set_package_wrapper
Brett Cannon06c9d962009-02-07 01:52:25 +0000496
497
Brett Cannon2cf03a82009-03-10 05:17:37 +0000498def set_loader(fxn):
499 """Set __loader__ on the returned module."""
Brett Cannonf522aea2012-01-16 11:46:22 -0500500 def set_loader_wrapper(self, *args, **kwargs):
Brett Cannon2cf03a82009-03-10 05:17:37 +0000501 module = fxn(self, *args, **kwargs)
Brett Cannon4802bec2013-03-13 10:41:36 -0700502 if getattr(module, '__loader__', None) is None:
Brett Cannon2cf03a82009-03-10 05:17:37 +0000503 module.__loader__ = self
504 return module
Brett Cannonf522aea2012-01-16 11:46:22 -0500505 _wrap(set_loader_wrapper, fxn)
506 return set_loader_wrapper
Brett Cannon2cf03a82009-03-10 05:17:37 +0000507
508
Brett Cannonce43ddf2009-03-12 22:28:55 +0000509def module_for_loader(fxn):
510 """Decorator to handle selecting the proper module for loaders.
511
Brett Cannon0e0d8a62009-03-15 00:00:19 +0000512 The decorated function is passed the module to use instead of the module
513 name. The module passed in to the function is either from sys.modules if
Brett Cannonefad00d2012-04-27 17:27:14 -0400514 it already exists or is a new module. If the module is new, then __name__
515 is set the first argument to the method, __loader__ is set to self, and
516 __package__ is set accordingly (if self.is_package() is defined) will be set
517 before it is passed to the decorated function (if self.is_package() does
518 not work for the module it will be set post-load).
519
520 If an exception is raised and the decorator created the module it is
521 subsequently removed from sys.modules.
Brett Cannonce43ddf2009-03-12 22:28:55 +0000522
Brett Cannon0e0d8a62009-03-15 00:00:19 +0000523 The decorator assumes that the decorated function takes the module name as
524 the second argument.
Brett Cannonce43ddf2009-03-12 22:28:55 +0000525
526 """
Brett Cannonf522aea2012-01-16 11:46:22 -0500527 def module_for_loader_wrapper(self, fullname, *args, **kwargs):
Brett Cannonce43ddf2009-03-12 22:28:55 +0000528 module = sys.modules.get(fullname)
Brett Cannon7bd329d2012-04-17 21:41:35 -0400529 is_reload = module is not None
Brett Cannonce43ddf2009-03-12 22:28:55 +0000530 if not is_reload:
531 # This must be done before open() is called as the 'io' module
532 # implicitly imports 'locale' and would otherwise trigger an
533 # infinite loop.
Brett Cannon17098a52012-05-04 13:52:49 -0400534 module = new_module(fullname)
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200535 # This must be done before putting the module in sys.modules
536 # (otherwise an optimization shortcut in import.c becomes wrong)
537 module.__initializing__ = True
Brett Cannonce43ddf2009-03-12 22:28:55 +0000538 sys.modules[fullname] = module
Brett Cannonefad00d2012-04-27 17:27:14 -0400539 module.__loader__ = self
540 try:
541 is_package = self.is_package(fullname)
542 except (ImportError, AttributeError):
543 pass
544 else:
545 if is_package:
546 module.__package__ = fullname
547 else:
548 module.__package__ = fullname.rpartition('.')[0]
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200549 else:
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200550 module.__initializing__ = True
Antoine Pitrou4f0338c2012-08-28 00:24:52 +0200551 try:
Brett Cannonefad00d2012-04-27 17:27:14 -0400552 # If __package__ was not set above, __import__() will do it later.
Brett Cannon61b14252010-07-03 21:48:25 +0000553 return fxn(self, module, *args, **kwargs)
Brett Cannonce43ddf2009-03-12 22:28:55 +0000554 except:
555 if not is_reload:
556 del sys.modules[fullname]
557 raise
Antoine Pitrouea3eb882012-05-17 18:55:59 +0200558 finally:
559 module.__initializing__ = False
Brett Cannonf522aea2012-01-16 11:46:22 -0500560 _wrap(module_for_loader_wrapper, fxn)
561 return module_for_loader_wrapper
Brett Cannonce43ddf2009-03-12 22:28:55 +0000562
563
564def _check_name(method):
565 """Decorator to verify that the module being requested matches the one the
566 loader can handle.
567
568 The first argument (self) must define _name which the second argument is
Ezio Melotti42da6632011-03-15 05:18:48 +0200569 compared against. If the comparison fails then ImportError is raised.
Brett Cannonce43ddf2009-03-12 22:28:55 +0000570
571 """
Brett Cannonc0499522012-05-11 14:48:41 -0400572 def _check_name_wrapper(self, name=None, *args, **kwargs):
573 if name is None:
574 name = self.name
575 elif self.name != name:
Brett Cannonbbb66802012-04-12 21:09:01 -0400576 raise ImportError("loader cannot handle %s" % name, name=name)
Brett Cannonce43ddf2009-03-12 22:28:55 +0000577 return method(self, name, *args, **kwargs)
Brett Cannonf522aea2012-01-16 11:46:22 -0500578 _wrap(_check_name_wrapper, method)
579 return _check_name_wrapper
Brett Cannonce43ddf2009-03-12 22:28:55 +0000580
581
Brett Cannona113ac52009-03-15 01:41:33 +0000582def _requires_builtin(fxn):
583 """Decorator to verify the named module is built-in."""
Brett Cannonf522aea2012-01-16 11:46:22 -0500584 def _requires_builtin_wrapper(self, fullname):
Brett Cannona113ac52009-03-15 01:41:33 +0000585 if fullname not in sys.builtin_module_names:
Florent Xicluna79d79a02012-07-07 13:16:44 +0200586 raise ImportError("{} is not a built-in module".format(fullname),
Brett Cannonbbb66802012-04-12 21:09:01 -0400587 name=fullname)
Brett Cannona113ac52009-03-15 01:41:33 +0000588 return fxn(self, fullname)
Brett Cannonf522aea2012-01-16 11:46:22 -0500589 _wrap(_requires_builtin_wrapper, fxn)
590 return _requires_builtin_wrapper
Brett Cannona113ac52009-03-15 01:41:33 +0000591
592
Brett Cannon8d110132009-03-15 02:20:16 +0000593def _requires_frozen(fxn):
594 """Decorator to verify the named module is frozen."""
Brett Cannonf522aea2012-01-16 11:46:22 -0500595 def _requires_frozen_wrapper(self, fullname):
Brett Cannon6f44d662012-04-15 16:08:47 -0400596 if not _imp.is_frozen(fullname):
Florent Xicluna79d79a02012-07-07 13:16:44 +0200597 raise ImportError("{} is not a frozen module".format(fullname),
Brett Cannonbbb66802012-04-12 21:09:01 -0400598 name=fullname)
Brett Cannon8d110132009-03-15 02:20:16 +0000599 return fxn(self, fullname)
Brett Cannonf522aea2012-01-16 11:46:22 -0500600 _wrap(_requires_frozen_wrapper, fxn)
601 return _requires_frozen_wrapper
Brett Cannon8d110132009-03-15 02:20:16 +0000602
603
Brett Cannonf410ce82012-08-10 17:41:23 -0400604def _find_module_shim(self, fullname):
605 """Try to find a loader for the specified module by delegating to
606 self.find_loader()."""
607 # Call find_loader(). If it returns a string (indicating this
608 # is a namespace package portion), generate a warning and
609 # return None.
610 loader, portions = self.find_loader(fullname)
611 if loader is None and len(portions):
612 msg = "Not importing directory {}: missing __init__"
613 _warnings.warn(msg.format(portions[0]), ImportWarning)
614 return loader
615
616
Brett Cannon569ff4f2013-01-11 18:09:25 -0500617def _validate_bytecode_header(data, source_stats=None, name=None, path=None):
618 """Validate the header of the passed-in bytecode against source_stats (if
619 given) and returning the bytecode that can be compiled by compile().
620
621 All other arguments are used to enhance error reporting.
622
623 ImportError is raised when the magic number is incorrect or the bytecode is
624 found to be stale. EOFError is raised when the data is found to be
625 truncated.
626
627 """
628 exc_details = {}
629 if name is not None:
630 exc_details['name'] = name
631 else:
632 # To prevent having to make all messages have a conditional name.
Brett Cannon686e8802013-01-25 13:49:19 -0500633 name = '<bytecode>'
Brett Cannon569ff4f2013-01-11 18:09:25 -0500634 if path is not None:
635 exc_details['path'] = path
636 magic = data[:4]
637 raw_timestamp = data[4:8]
638 raw_size = data[8:12]
639 if magic != _MAGIC_BYTES:
Brett Cannondaf4daa2013-04-01 13:25:40 -0400640 message = 'bad magic number in {!r}: {!r}'.format(name, magic)
641 _verbose_message(message)
642 raise ImportError(message, **exc_details)
Brett Cannon569ff4f2013-01-11 18:09:25 -0500643 elif len(raw_timestamp) != 4:
Brett Cannon686e8802013-01-25 13:49:19 -0500644 message = 'incomplete timestamp in {!r}'.format(name)
Brett Cannon569ff4f2013-01-11 18:09:25 -0500645 _verbose_message(message)
646 raise EOFError(message)
647 elif len(raw_size) != 4:
Brett Cannon686e8802013-01-25 13:49:19 -0500648 message = 'incomplete size in {!r}'.format(name)
Brett Cannon569ff4f2013-01-11 18:09:25 -0500649 _verbose_message(message)
650 raise EOFError(message)
651 if source_stats is not None:
652 try:
653 source_mtime = int(source_stats['mtime'])
654 except KeyError:
655 pass
656 else:
657 if _r_long(raw_timestamp) != source_mtime:
658 message = 'bytecode is stale for {!r}'.format(name)
659 _verbose_message(message)
660 raise ImportError(message, **exc_details)
661 try:
662 source_size = source_stats['size'] & 0xFFFFFFFF
663 except KeyError:
664 pass
665 else:
666 if _r_long(raw_size) != source_size:
667 raise ImportError("bytecode is stale for {!r}".format(name),
668 **exc_details)
669 return data[12:]
670
671
672def _compile_bytecode(data, name=None, bytecode_path=None, source_path=None):
673 """Compile bytecode as returned by _validate_bytecode_header()."""
674 code = marshal.loads(data)
675 if isinstance(code, _code_type):
676 _verbose_message('code object from {!r}', bytecode_path)
677 if source_path is not None:
678 _imp._fix_co_filename(code, source_path)
679 return code
680 else:
681 raise ImportError("Non-code object in {!r}".format(bytecode_path),
682 name=name, path=bytecode_path)
Brett Cannonf410ce82012-08-10 17:41:23 -0400683
Brett Cannon14581d52013-01-26 08:48:36 -0500684def _code_to_bytecode(code, mtime=0, source_size=0):
685 """Compile a code object into bytecode for writing out to a byte-compiled
686 file."""
687 data = bytearray(_MAGIC_BYTES)
688 data.extend(_w_long(mtime))
689 data.extend(_w_long(source_size))
690 data.extend(marshal.dumps(code))
691 return data
692
Brett Cannonf410ce82012-08-10 17:41:23 -0400693
Brett Cannone9103d22009-03-12 22:37:06 +0000694# Loaders #####################################################################
Brett Cannonce43ddf2009-03-12 22:28:55 +0000695
Brett Cannon5abdc932009-01-22 22:43:07 +0000696class BuiltinImporter:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000697
Brett Cannon7aa21f72009-03-15 00:53:05 +0000698 """Meta path import for built-in modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000699
Brett Cannon7aa21f72009-03-15 00:53:05 +0000700 All methods are either class or static methods to avoid the need to
701 instantiate the class.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000702
703 """
704
Brett Cannon5abdc932009-01-22 22:43:07 +0000705 @classmethod
Eric V. Smith984b11f2012-05-24 20:21:04 -0400706 def module_repr(cls, module):
707 return "<module '{}' (built-in)>".format(module.__name__)
708
709 @classmethod
Brett Cannon5abdc932009-01-22 22:43:07 +0000710 def find_module(cls, fullname, path=None):
Brett Cannon7aa21f72009-03-15 00:53:05 +0000711 """Find the built-in module.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000712
713 If 'path' is ever specified then the search is considered a failure.
714
715 """
716 if path is not None:
717 return None
Brett Cannon6f44d662012-04-15 16:08:47 -0400718 return cls if _imp.is_builtin(fullname) else None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000719
Brett Cannon78246b62009-01-25 04:56:30 +0000720 @classmethod
Brett Cannon435aad82009-03-04 16:07:00 +0000721 @set_package
Brett Cannon2cf03a82009-03-10 05:17:37 +0000722 @set_loader
Brett Cannona113ac52009-03-15 01:41:33 +0000723 @_requires_builtin
Brett Cannon78246b62009-01-25 04:56:30 +0000724 def load_module(cls, fullname):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000725 """Load a built-in module."""
Brett Cannond2e7b332009-02-17 02:45:03 +0000726 is_reload = fullname in sys.modules
727 try:
Nick Coghlan42c07662012-07-31 21:14:18 +1000728 return _call_with_frames_removed(_imp.init_builtin, fullname)
Brett Cannond2e7b332009-02-17 02:45:03 +0000729 except:
730 if not is_reload and fullname in sys.modules:
731 del sys.modules[fullname]
732 raise
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000733
Brett Cannona113ac52009-03-15 01:41:33 +0000734 @classmethod
735 @_requires_builtin
736 def get_code(cls, fullname):
737 """Return None as built-in modules do not have code objects."""
738 return None
739
740 @classmethod
741 @_requires_builtin
742 def get_source(cls, fullname):
743 """Return None as built-in modules do not have source code."""
744 return None
745
746 @classmethod
747 @_requires_builtin
748 def is_package(cls, fullname):
Florent Xicluna79d79a02012-07-07 13:16:44 +0200749 """Return False as built-in modules are never packages."""
Brett Cannona113ac52009-03-15 01:41:33 +0000750 return False
751
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000752
Brett Cannon5abdc932009-01-22 22:43:07 +0000753class FrozenImporter:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000754
Brett Cannon7aa21f72009-03-15 00:53:05 +0000755 """Meta path import for frozen modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000756
Brett Cannon7aa21f72009-03-15 00:53:05 +0000757 All methods are either class or static methods to avoid the need to
758 instantiate the class.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000759
Brett Cannon5abdc932009-01-22 22:43:07 +0000760 """
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000761
Brett Cannon5abdc932009-01-22 22:43:07 +0000762 @classmethod
Eric V. Smith984b11f2012-05-24 20:21:04 -0400763 def module_repr(cls, m):
764 return "<module '{}' (frozen)>".format(m.__name__)
765
766 @classmethod
Brett Cannon5abdc932009-01-22 22:43:07 +0000767 def find_module(cls, fullname, path=None):
768 """Find a frozen module."""
Brett Cannon6f44d662012-04-15 16:08:47 -0400769 return cls if _imp.is_frozen(fullname) else None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000770
Brett Cannon5abdc932009-01-22 22:43:07 +0000771 @classmethod
Brett Cannon435aad82009-03-04 16:07:00 +0000772 @set_package
Brett Cannon2cf03a82009-03-10 05:17:37 +0000773 @set_loader
Brett Cannon8d110132009-03-15 02:20:16 +0000774 @_requires_frozen
Brett Cannon5abdc932009-01-22 22:43:07 +0000775 def load_module(cls, fullname):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000776 """Load a frozen module."""
Brett Cannond2e7b332009-02-17 02:45:03 +0000777 is_reload = fullname in sys.modules
778 try:
Nick Coghlan42c07662012-07-31 21:14:18 +1000779 m = _call_with_frames_removed(_imp.init_frozen, fullname)
Eric V. Smith984b11f2012-05-24 20:21:04 -0400780 # Let our own module_repr() method produce a suitable repr.
781 del m.__file__
782 return m
Brett Cannond2e7b332009-02-17 02:45:03 +0000783 except:
784 if not is_reload and fullname in sys.modules:
785 del sys.modules[fullname]
786 raise
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000787
Brett Cannon8d110132009-03-15 02:20:16 +0000788 @classmethod
789 @_requires_frozen
790 def get_code(cls, fullname):
791 """Return the code object for the frozen module."""
Brett Cannon6f44d662012-04-15 16:08:47 -0400792 return _imp.get_frozen_object(fullname)
Brett Cannon8d110132009-03-15 02:20:16 +0000793
794 @classmethod
795 @_requires_frozen
796 def get_source(cls, fullname):
797 """Return None as frozen modules do not have source code."""
798 return None
799
800 @classmethod
801 @_requires_frozen
802 def is_package(cls, fullname):
Philip Jenvey688a5512012-08-10 16:21:35 -0700803 """Return True if the frozen module is a package."""
Brett Cannon6f44d662012-04-15 16:08:47 -0400804 return _imp.is_frozen_package(fullname)
Brett Cannon8d110132009-03-15 02:20:16 +0000805
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000806
Nick Coghlanff794862012-08-02 21:45:24 +1000807class WindowsRegistryFinder:
Martin v. Löwise3010a82012-07-28 21:33:05 +0200808
Nick Coghlanff794862012-08-02 21:45:24 +1000809 """Meta path finder for modules declared in the Windows registry.
Martin v. Löwise3010a82012-07-28 21:33:05 +0200810 """
811
812 REGISTRY_KEY = (
813 "Software\\Python\\PythonCore\\{sys_version}"
814 "\\Modules\\{fullname}")
815 REGISTRY_KEY_DEBUG = (
816 "Software\\Python\\PythonCore\\{sys_version}"
817 "\\Modules\\{fullname}\\Debug")
818 DEBUG_BUILD = False # Changed in _setup()
819
820 @classmethod
821 def _open_registry(cls, key):
822 try:
823 return _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, key)
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200824 except OSError:
Martin v. Löwise3010a82012-07-28 21:33:05 +0200825 return _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key)
826
827 @classmethod
828 def _search_registry(cls, fullname):
829 if cls.DEBUG_BUILD:
830 registry_key = cls.REGISTRY_KEY_DEBUG
831 else:
832 registry_key = cls.REGISTRY_KEY
833 key = registry_key.format(fullname=fullname,
834 sys_version=sys.version[:3])
835 try:
836 with cls._open_registry(key) as hkey:
837 filepath = _winreg.QueryValue(hkey, "")
Andrew Svetlov2606a6f2012-12-19 14:33:35 +0200838 except OSError:
Martin v. Löwise3010a82012-07-28 21:33:05 +0200839 return None
840 return filepath
841
842 @classmethod
843 def find_module(cls, fullname, path=None):
844 """Find module named in the registry."""
845 filepath = cls._search_registry(fullname)
846 if filepath is None:
847 return None
848 try:
849 _os.stat(filepath)
850 except OSError:
851 return None
852 for loader, suffixes, _ in _get_supported_file_loaders():
853 if filepath.endswith(tuple(suffixes)):
854 return loader(fullname, filepath)
855
856
Brett Cannon61b14252010-07-03 21:48:25 +0000857class _LoaderBasics:
858
859 """Base class of common code needed by both SourceLoader and
Brett Cannon938d44d2012-04-22 19:58:33 -0400860 SourcelessFileLoader."""
Brett Cannon61b14252010-07-03 21:48:25 +0000861
862 def is_package(self, fullname):
863 """Concrete implementation of InspectLoader.is_package by checking if
864 the path returned by get_filename has a filename of '__init__.py'."""
Brett Cannoned672d62012-04-20 21:19:53 -0400865 filename = _path_split(self.get_filename(fullname))[1]
Brett Cannonea0b8232012-06-15 20:00:53 -0400866 filename_base = filename.rsplit('.', 1)[0]
867 tail_name = fullname.rpartition('.')[2]
868 return filename_base == '__init__' and tail_name != '__init__'
Brett Cannon61b14252010-07-03 21:48:25 +0000869
Brett Cannon61b14252010-07-03 21:48:25 +0000870 @module_for_loader
871 def _load_module(self, module, *, sourceless=False):
872 """Helper for load_module able to handle either source or sourceless
873 loading."""
874 name = module.__name__
875 code_object = self.get_code(name)
876 module.__file__ = self.get_filename(name)
877 if not sourceless:
Brett Cannon19a2f592012-07-09 13:58:07 -0400878 try:
879 module.__cached__ = cache_from_source(module.__file__)
880 except NotImplementedError:
881 module.__cached__ = module.__file__
Brett Cannon61b14252010-07-03 21:48:25 +0000882 else:
883 module.__cached__ = module.__file__
Brett Cannon61b14252010-07-03 21:48:25 +0000884 if self.is_package(name):
Brett Cannoned672d62012-04-20 21:19:53 -0400885 module.__path__ = [_path_split(module.__file__)[0]]
Brett Cannon4802bec2013-03-13 10:41:36 -0700886 # __package__ and __loader set by @module_for_loader.
Nick Coghlan42c07662012-07-31 21:14:18 +1000887 _call_with_frames_removed(exec, code_object, module.__dict__)
Brett Cannon61b14252010-07-03 21:48:25 +0000888 return module
889
890
891class SourceLoader(_LoaderBasics):
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000892
Raymond Hettingercd92f372011-01-13 02:31:25 +0000893 def path_mtime(self, path):
Raymond Hettingerd958ea72011-01-13 19:08:04 +0000894 """Optional method that returns the modification time (an int) for the
895 specified path, where path is a str.
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000896 """
897 raise NotImplementedError
898
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100899 def path_stats(self, path):
900 """Optional method returning a metadata dict for the specified path
901 to by the path (str).
902 Possible keys:
903 - 'mtime' (mandatory) is the numeric timestamp of last source
904 code modification;
905 - 'size' (optional) is the size in bytes of the source code.
906
907 Implementing this method allows the loader to read bytecode files.
908 """
909 return {'mtime': self.path_mtime(path)}
910
Nick Coghlana5087702012-08-24 18:32:40 +1000911 def _cache_bytecode(self, source_path, cache_path, data):
912 """Optional method which writes data (bytes) to a file path (a str).
913
914 Implementing this method allows for the writing of bytecode files.
915
916 The source path is needed in order to correctly transfer permissions
917 """
918 # For backwards compatibility, we delegate to set_data()
919 return self.set_data(cache_path, data)
920
Raymond Hettingercd92f372011-01-13 02:31:25 +0000921 def set_data(self, path, data):
Raymond Hettingerd958ea72011-01-13 19:08:04 +0000922 """Optional method which writes data (bytes) to a file path (a str).
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000923
924 Implementing this method allows for the writing of bytecode files.
925
926 """
927 raise NotImplementedError
928
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000929
930 def get_source(self, fullname):
931 """Concrete implementation of InspectLoader.get_source."""
932 import tokenize
933 path = self.get_filename(fullname)
934 try:
935 source_bytes = self.get_data(path)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200936 except OSError as exc:
Brett Cannonbbb66802012-04-12 21:09:01 -0400937 raise ImportError("source not available through get_data()",
Nick Coghlan2824cb52012-07-15 22:12:14 +1000938 name=fullname) from exc
939 readsource = _io.BytesIO(source_bytes).readline
940 try:
941 encoding = tokenize.detect_encoding(readsource)
942 except SyntaxError as exc:
943 raise ImportError("Failed to detect encoding",
944 name=fullname) from exc
Brett Cannon418182e2010-07-03 22:32:41 +0000945 newline_decoder = _io.IncrementalNewlineDecoder(None, True)
Nick Coghlan2824cb52012-07-15 22:12:14 +1000946 try:
947 return newline_decoder.decode(source_bytes.decode(encoding[0]))
948 except UnicodeDecodeError as exc:
949 raise ImportError("Failed to decode source file",
950 name=fullname) from exc
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000951
Brett Cannon14581d52013-01-26 08:48:36 -0500952 def source_to_code(self, data, path, *, _optimize=-1):
Brett Cannon5650e4f2012-11-18 10:03:31 -0500953 """Return the code object compiled from source.
954
955 The 'data' argument can be any object type that compile() supports.
956 """
957 return _call_with_frames_removed(compile, data, path, 'exec',
Brett Cannon14581d52013-01-26 08:48:36 -0500958 dont_inherit=True, optimize=_optimize)
Brett Cannon5650e4f2012-11-18 10:03:31 -0500959
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000960 def get_code(self, fullname):
961 """Concrete implementation of InspectLoader.get_code.
962
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100963 Reading of bytecode requires path_stats to be implemented. To write
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000964 bytecode, set_data must also be implemented.
965
966 """
967 source_path = self.get_filename(fullname)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000968 source_mtime = None
Brett Cannon19a2f592012-07-09 13:58:07 -0400969 try:
970 bytecode_path = cache_from_source(source_path)
971 except NotImplementedError:
972 bytecode_path = None
973 else:
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000974 try:
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100975 st = self.path_stats(source_path)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000976 except NotImplementedError:
977 pass
978 else:
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100979 source_mtime = int(st['mtime'])
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000980 try:
981 data = self.get_data(bytecode_path)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200982 except OSError:
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000983 pass
984 else:
Brett Cannon61b14252010-07-03 21:48:25 +0000985 try:
Brett Cannon569ff4f2013-01-11 18:09:25 -0500986 bytes_data = _validate_bytecode_header(data,
987 source_stats=st, name=fullname,
988 path=bytecode_path)
Brett Cannon61b14252010-07-03 21:48:25 +0000989 except (ImportError, EOFError):
990 pass
991 else:
Brett Cannon17098a52012-05-04 13:52:49 -0400992 _verbose_message('{} matches {}', bytecode_path,
Brett Cannonfd074152012-04-14 14:10:13 -0400993 source_path)
Brett Cannon569ff4f2013-01-11 18:09:25 -0500994 return _compile_bytecode(bytes_data, name=fullname,
995 bytecode_path=bytecode_path,
996 source_path=source_path)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000997 source_bytes = self.get_data(source_path)
Eric Snowa6cfb282012-12-04 23:43:43 -0800998 code_object = self.source_to_code(source_bytes, source_path)
Brett Cannon17098a52012-05-04 13:52:49 -0400999 _verbose_message('code object from {}', source_path)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001000 if (not sys.dont_write_bytecode and bytecode_path is not None and
Brett Cannon14581d52013-01-26 08:48:36 -05001001 source_mtime is not None):
1002 data = _code_to_bytecode(code_object, source_mtime,
1003 len(source_bytes))
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001004 try:
Nick Coghlana5087702012-08-24 18:32:40 +10001005 self._cache_bytecode(source_path, bytecode_path, data)
Brett Cannon17098a52012-05-04 13:52:49 -04001006 _verbose_message('wrote {!r}', bytecode_path)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001007 except NotImplementedError:
1008 pass
1009 return code_object
1010
Brett Cannon61b14252010-07-03 21:48:25 +00001011 def load_module(self, fullname):
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001012 """Concrete implementation of Loader.load_module.
1013
1014 Requires ExecutionLoader.get_filename and ResourceLoader.get_data to be
1015 implemented to load source code. Use of bytecode is dictated by whether
1016 get_code uses/writes bytecode.
1017
1018 """
Brett Cannon61b14252010-07-03 21:48:25 +00001019 return self._load_module(fullname)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001020
1021
Brett Cannon938d44d2012-04-22 19:58:33 -04001022class FileLoader:
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001023
Brett Cannon61b14252010-07-03 21:48:25 +00001024 """Base file loader class which implements the loader protocol methods that
1025 require file system usage."""
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001026
1027 def __init__(self, fullname, path):
Brett Cannon61b14252010-07-03 21:48:25 +00001028 """Cache the module name and the path to the file found by the
1029 finder."""
Brett Cannon938d44d2012-04-22 19:58:33 -04001030 self.name = fullname
1031 self.path = path
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001032
1033 @_check_name
Brett Cannonc0499522012-05-11 14:48:41 -04001034 def load_module(self, fullname):
1035 """Load a module from a file."""
Nick Coghlan5c6eba32012-05-27 17:49:58 +10001036 # Issue #14857: Avoid the zero-argument form so the implementation
1037 # of that form can be updated without breaking the frozen module
1038 return super(FileLoader, self).load_module(fullname)
Brett Cannonc0499522012-05-11 14:48:41 -04001039
1040 @_check_name
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001041 def get_filename(self, fullname):
1042 """Return the path to the source file as found by the finder."""
Brett Cannon938d44d2012-04-22 19:58:33 -04001043 return self.path
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001044
Brett Cannon61b14252010-07-03 21:48:25 +00001045 def get_data(self, path):
1046 """Return the data from path as raw bytes."""
Florent Xicluna764d6122010-09-03 19:55:26 +00001047 with _io.FileIO(path, 'r') as file:
Brett Cannon61b14252010-07-03 21:48:25 +00001048 return file.read()
1049
1050
Brett Cannon938d44d2012-04-22 19:58:33 -04001051class SourceFileLoader(FileLoader, SourceLoader):
Brett Cannon61b14252010-07-03 21:48:25 +00001052
1053 """Concrete implementation of SourceLoader using the file system."""
1054
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001055 def path_stats(self, path):
Philip Jenvey688a5512012-08-10 16:21:35 -07001056 """Return the metadata for the path."""
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001057 st = _os.stat(path)
1058 return {'mtime': st.st_mtime, 'size': st.st_size}
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001059
Nick Coghlana5087702012-08-24 18:32:40 +10001060 def _cache_bytecode(self, source_path, bytecode_path, data):
1061 # Adapt between the two APIs
Brett Cannonba0a3ed2012-08-24 13:48:39 -04001062 try:
1063 mode = _os.stat(source_path).st_mode
1064 except OSError:
1065 mode = 0o666
Nick Coghlaneb8d6272012-10-19 23:32:00 +10001066 # We always ensure write access so we can update cached files
1067 # later even when the source files are read-only on Windows (#6074)
1068 mode |= 0o200
Brett Cannonba0a3ed2012-08-24 13:48:39 -04001069 return self.set_data(bytecode_path, data, _mode=mode)
Nick Coghlana5087702012-08-24 18:32:40 +10001070
Brett Cannonba0a3ed2012-08-24 13:48:39 -04001071 def set_data(self, path, data, *, _mode=0o666):
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001072 """Write bytes data to a file."""
Brett Cannoned672d62012-04-20 21:19:53 -04001073 parent, filename = _path_split(path)
Brett Cannonee6d6472010-08-22 22:19:11 +00001074 path_parts = []
1075 # Figure out what directories are missing.
1076 while parent and not _path_isdir(parent):
Brett Cannoned672d62012-04-20 21:19:53 -04001077 parent, part = _path_split(parent)
Brett Cannonee6d6472010-08-22 22:19:11 +00001078 path_parts.append(part)
1079 # Create needed directories.
1080 for part in reversed(path_parts):
1081 parent = _path_join(parent, part)
1082 try:
1083 _os.mkdir(parent)
Florent Xicluna68f71a32011-10-28 16:06:23 +02001084 except FileExistsError:
Brett Cannonee6d6472010-08-22 22:19:11 +00001085 # Probably another Python process already created the dir.
Florent Xicluna68f71a32011-10-28 16:06:23 +02001086 continue
Trent Nelsond783c8e2012-10-16 07:47:34 -04001087 except OSError as exc:
1088 # Could be a permission error, read-only filesystem: just forget
1089 # about writing the data.
1090 _verbose_message('could not create {!r}: {!r}', parent, exc)
Florent Xicluna68f71a32011-10-28 16:06:23 +02001091 return
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001092 try:
Brett Cannonba0a3ed2012-08-24 13:48:39 -04001093 _write_atomic(path, data, _mode)
Brett Cannon17098a52012-05-04 13:52:49 -04001094 _verbose_message('created {!r}', path)
Trent Nelsond783c8e2012-10-16 07:47:34 -04001095 except OSError as exc:
1096 # Same as above: just don't write the bytecode.
1097 _verbose_message('could not create {!r}: {!r}', path, exc)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +00001098
1099
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +02001100class SourcelessFileLoader(FileLoader, _LoaderBasics):
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001101
Brett Cannon61b14252010-07-03 21:48:25 +00001102 """Loader which handles sourceless file imports."""
Brett Cannon91cf8822009-02-21 05:41:15 +00001103
Brett Cannon61b14252010-07-03 21:48:25 +00001104 def load_module(self, fullname):
1105 return self._load_module(fullname, sourceless=True)
Brett Cannon69194272009-07-20 04:23:48 +00001106
Brett Cannon91cf8822009-02-21 05:41:15 +00001107 def get_code(self, fullname):
Brett Cannon61b14252010-07-03 21:48:25 +00001108 path = self.get_filename(fullname)
1109 data = self.get_data(path)
Brett Cannon569ff4f2013-01-11 18:09:25 -05001110 bytes_data = _validate_bytecode_header(data, name=fullname, path=path)
1111 return _compile_bytecode(bytes_data, name=fullname, bytecode_path=path)
Brett Cannon91cf8822009-02-21 05:41:15 +00001112
Brett Cannond43b30b2009-03-10 03:29:23 +00001113 def get_source(self, fullname):
Brett Cannon61b14252010-07-03 21:48:25 +00001114 """Return None as there is no source code."""
1115 return None
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001116
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001117
Brett Cannonac9f2f32012-08-10 13:47:54 -04001118# Filled in by _setup().
1119EXTENSION_SUFFIXES = []
1120
1121
Brett Cannon938d44d2012-04-22 19:58:33 -04001122class ExtensionFileLoader:
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001123
Brett Cannone9103d22009-03-12 22:37:06 +00001124 """Loader for extension modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001125
Brett Cannone9103d22009-03-12 22:37:06 +00001126 The constructor is designed to work with FileFinder.
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001127
1128 """
1129
Brett Cannon61b14252010-07-03 21:48:25 +00001130 def __init__(self, name, path):
Brett Cannon938d44d2012-04-22 19:58:33 -04001131 self.name = name
1132 self.path = path
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001133
Brett Cannone9103d22009-03-12 22:37:06 +00001134 @_check_name
1135 @set_package
1136 @set_loader
1137 def load_module(self, fullname):
1138 """Load an extension module."""
1139 is_reload = fullname in sys.modules
1140 try:
Nick Coghlan42c07662012-07-31 21:14:18 +10001141 module = _call_with_frames_removed(_imp.load_dynamic,
1142 fullname, self.path)
Brett Cannon17098a52012-05-04 13:52:49 -04001143 _verbose_message('extension module loaded from {!r}', self.path)
Brett Cannonb428f472012-08-11 19:43:29 -04001144 if self.is_package(fullname) and not hasattr(module, '__path__'):
Brett Cannonac9f2f32012-08-10 13:47:54 -04001145 module.__path__ = [_path_split(self.path)[0]]
Brett Cannonfd074152012-04-14 14:10:13 -04001146 return module
Brett Cannone9103d22009-03-12 22:37:06 +00001147 except:
1148 if not is_reload and fullname in sys.modules:
1149 del sys.modules[fullname]
1150 raise
1151
Brett Cannone9103d22009-03-12 22:37:06 +00001152 def is_package(self, fullname):
Philip Jenvey688a5512012-08-10 16:21:35 -07001153 """Return True if the extension module is a package."""
Brett Cannonac9f2f32012-08-10 13:47:54 -04001154 file_name = _path_split(self.path)[1]
Philip Jenvey731d48a2012-08-10 11:53:54 -07001155 return any(file_name == '__init__' + suffix
1156 for suffix in EXTENSION_SUFFIXES)
Brett Cannone9103d22009-03-12 22:37:06 +00001157
Brett Cannone9103d22009-03-12 22:37:06 +00001158 def get_code(self, fullname):
1159 """Return None as an extension module cannot create a code object."""
1160 return None
1161
Brett Cannone9103d22009-03-12 22:37:06 +00001162 def get_source(self, fullname):
1163 """Return None as extension modules have no source code."""
1164 return None
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001165
1166
Eric V. Smith984b11f2012-05-24 20:21:04 -04001167class _NamespacePath:
1168 """Represents a namespace package's path. It uses the module name
1169 to find its parent module, and from there it looks up the parent's
1170 __path__. When this changes, the module's own path is recomputed,
Benjamin Petersondebf64c2012-11-12 16:48:17 -05001171 using path_finder. For top-level modules, the parent module's path
Eric V. Smith984b11f2012-05-24 20:21:04 -04001172 is sys.path."""
1173
1174 def __init__(self, name, path, path_finder):
1175 self._name = name
1176 self._path = path
1177 self._last_parent_path = tuple(self._get_parent_path())
1178 self._path_finder = path_finder
1179
1180 def _find_parent_path_names(self):
1181 """Returns a tuple of (parent-module-name, parent-path-attr-name)"""
1182 parent, dot, me = self._name.rpartition('.')
1183 if dot == '':
1184 # This is a top-level module. sys.path contains the parent path.
1185 return 'sys', 'path'
1186 # Not a top-level module. parent-module.__path__ contains the
1187 # parent path.
1188 return parent, '__path__'
1189
1190 def _get_parent_path(self):
1191 parent_module_name, path_attr_name = self._find_parent_path_names()
1192 return getattr(sys.modules[parent_module_name], path_attr_name)
1193
1194 def _recalculate(self):
1195 # If the parent's path has changed, recalculate _path
1196 parent_path = tuple(self._get_parent_path()) # Make a copy
1197 if parent_path != self._last_parent_path:
1198 loader, new_path = self._path_finder(self._name, parent_path)
1199 # Note that no changes are made if a loader is returned, but we
1200 # do remember the new parent path
1201 if loader is None:
1202 self._path = new_path
1203 self._last_parent_path = parent_path # Save the copy
1204 return self._path
1205
1206 def __iter__(self):
1207 return iter(self._recalculate())
1208
1209 def __len__(self):
1210 return len(self._recalculate())
1211
1212 def __repr__(self):
Florent Xicluna79d79a02012-07-07 13:16:44 +02001213 return "_NamespacePath({!r})".format(self._path)
Eric V. Smith984b11f2012-05-24 20:21:04 -04001214
1215 def __contains__(self, item):
1216 return item in self._recalculate()
1217
1218 def append(self, item):
1219 self._path.append(item)
1220
1221
1222class NamespaceLoader:
1223 def __init__(self, name, path, path_finder):
1224 self._path = _NamespacePath(name, path, path_finder)
1225
1226 @classmethod
1227 def module_repr(cls, module):
1228 return "<module '{}' (namespace)>".format(module.__name__)
1229
Eric V. Smith984b11f2012-05-24 20:21:04 -04001230 @module_for_loader
1231 def load_module(self, module):
1232 """Load a namespace module."""
1233 _verbose_message('namespace module loaded with path {!r}', self._path)
1234 module.__path__ = self._path
1235 return module
1236
1237
Brett Cannone9103d22009-03-12 22:37:06 +00001238# Finders #####################################################################
Brett Cannon4afab6b2009-02-21 03:31:35 +00001239
Brett Cannonf7e5a8c2009-02-05 02:52:18 +00001240class PathFinder:
Brett Cannon1d376682009-02-02 19:19:36 +00001241
Nick Coghlan49417742012-08-02 23:03:58 +10001242 """Meta path finder for sys.path and package __path__ attributes."""
Brett Cannon1d376682009-02-02 19:19:36 +00001243
Brett Cannonf7e5a8c2009-02-05 02:52:18 +00001244 @classmethod
Brett Cannonf4dc9202012-08-10 12:21:12 -04001245 def invalidate_caches(cls):
1246 """Call the invalidate_caches() method on all path entry finders
1247 stored in sys.path_importer_caches (where implemented)."""
1248 for finder in sys.path_importer_cache.values():
1249 if hasattr(finder, 'invalidate_caches'):
1250 finder.invalidate_caches()
1251
1252 @classmethod
Brett Cannone0d88a12012-04-25 20:54:04 -04001253 def _path_hooks(cls, path):
Brett Cannon32732e32009-02-15 05:48:13 +00001254 """Search sequence of hooks for a finder for 'path'.
Brett Cannon1d376682009-02-02 19:19:36 +00001255
Brett Cannon32732e32009-02-15 05:48:13 +00001256 If 'hooks' is false then use sys.path_hooks.
Brett Cannon1d376682009-02-02 19:19:36 +00001257
1258 """
Brett Cannone0d88a12012-04-25 20:54:04 -04001259 if not sys.path_hooks:
1260 _warnings.warn('sys.path_hooks is empty', ImportWarning)
1261 for hook in sys.path_hooks:
Brett Cannon1d376682009-02-02 19:19:36 +00001262 try:
1263 return hook(path)
1264 except ImportError:
1265 continue
1266 else:
Brett Cannonaa936422012-04-27 15:30:58 -04001267 return None
Brett Cannon1d376682009-02-02 19:19:36 +00001268
Brett Cannonf7e5a8c2009-02-05 02:52:18 +00001269 @classmethod
Brett Cannone0d88a12012-04-25 20:54:04 -04001270 def _path_importer_cache(cls, path):
Nick Coghlan49417742012-08-02 23:03:58 +10001271 """Get the finder for the path entry from sys.path_importer_cache.
Brett Cannon1d376682009-02-02 19:19:36 +00001272
Nick Coghlan49417742012-08-02 23:03:58 +10001273 If the path entry is not in the cache, find the appropriate finder
1274 and cache it. If no finder is available, store None.
Brett Cannon1d376682009-02-02 19:19:36 +00001275
1276 """
Brett Cannonf58d45c2012-02-16 18:12:00 -05001277 if path == '':
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001278 path = '.'
Brett Cannon1d376682009-02-02 19:19:36 +00001279 try:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +00001280 finder = sys.path_importer_cache[path]
Brett Cannon1d376682009-02-02 19:19:36 +00001281 except KeyError:
Brett Cannonf58d45c2012-02-16 18:12:00 -05001282 finder = cls._path_hooks(path)
Brett Cannon1d376682009-02-02 19:19:36 +00001283 sys.path_importer_cache[path] = finder
Brett Cannon1d376682009-02-02 19:19:36 +00001284 return finder
1285
Brett Cannonf7e5a8c2009-02-05 02:52:18 +00001286 @classmethod
Eric V. Smith984b11f2012-05-24 20:21:04 -04001287 def _get_loader(cls, fullname, path):
1288 """Find the loader or namespace_path for this module/package name."""
1289 # If this ends up being a namespace package, namespace_path is
1290 # the list of paths that will become its __path__
1291 namespace_path = []
1292 for entry in path:
Barry Warsaw82c1c782012-11-20 15:22:51 -05001293 if not isinstance(entry, (str, bytes)):
1294 continue
Eric V. Smith984b11f2012-05-24 20:21:04 -04001295 finder = cls._path_importer_cache(entry)
1296 if finder is not None:
1297 if hasattr(finder, 'find_loader'):
1298 loader, portions = finder.find_loader(fullname)
1299 else:
1300 loader = finder.find_module(fullname)
1301 portions = []
1302 if loader is not None:
1303 # We found a loader: return it immediately.
Brett Cannonf4dc9202012-08-10 12:21:12 -04001304 return loader, namespace_path
Eric V. Smith984b11f2012-05-24 20:21:04 -04001305 # This is possibly part of a namespace package.
1306 # Remember these path entries (if any) for when we
1307 # create a namespace package, and continue iterating
1308 # on path.
1309 namespace_path.extend(portions)
1310 else:
Brett Cannonf4dc9202012-08-10 12:21:12 -04001311 return None, namespace_path
Eric V. Smith984b11f2012-05-24 20:21:04 -04001312
1313 @classmethod
Brett Cannonf7e5a8c2009-02-05 02:52:18 +00001314 def find_module(cls, fullname, path=None):
Brett Cannon7aa21f72009-03-15 00:53:05 +00001315 """Find the module on sys.path or 'path' based on sys.path_hooks and
1316 sys.path_importer_cache."""
Brett Cannon7bd329d2012-04-17 21:41:35 -04001317 if path is None:
Brett Cannon1d376682009-02-02 19:19:36 +00001318 path = sys.path
Eric V. Smith984b11f2012-05-24 20:21:04 -04001319 loader, namespace_path = cls._get_loader(fullname, path)
1320 if loader is not None:
1321 return loader
Brett Cannon1d376682009-02-02 19:19:36 +00001322 else:
Eric V. Smith984b11f2012-05-24 20:21:04 -04001323 if namespace_path:
1324 # We found at least one namespace path. Return a
1325 # loader which can create the namespace package.
1326 return NamespaceLoader(fullname, namespace_path, cls._get_loader)
1327 else:
1328 return None
Brett Cannon1d376682009-02-02 19:19:36 +00001329
1330
Brett Cannon938d44d2012-04-22 19:58:33 -04001331class FileFinder:
Brett Cannone9103d22009-03-12 22:37:06 +00001332
Brett Cannon61b14252010-07-03 21:48:25 +00001333 """File-based finder.
Brett Cannone9103d22009-03-12 22:37:06 +00001334
Brett Cannon938d44d2012-04-22 19:58:33 -04001335 Interactions with the file system are cached for performance, being
1336 refreshed when the directory the finder is handling has been modified.
Brett Cannone9103d22009-03-12 22:37:06 +00001337
1338 """
1339
Brett Cannon61b14252010-07-03 21:48:25 +00001340 def __init__(self, path, *details):
Brett Cannon938d44d2012-04-22 19:58:33 -04001341 """Initialize with the path to search on and a variable number of
Eric Snow5b499622013-02-16 22:23:48 -07001342 2-tuples containing the loader and the file suffixes the loader
1343 recognizes."""
Brett Cannonac9f2f32012-08-10 13:47:54 -04001344 loaders = []
1345 for loader, suffixes in details:
1346 loaders.extend((suffix, loader) for suffix in suffixes)
1347 self._loaders = loaders
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001348 # Base (directory) path
1349 self.path = path or '.'
1350 self._path_mtime = -1
1351 self._path_cache = set()
Antoine Pitroub5c793a2012-02-20 22:06:59 +01001352 self._relaxed_path_cache = set()
Brett Cannonb46a1792012-02-27 18:15:42 -05001353
1354 def invalidate_caches(self):
1355 """Invalidate the directory mtime."""
1356 self._path_mtime = -1
Brett Cannone9103d22009-03-12 22:37:06 +00001357
Brett Cannonf410ce82012-08-10 17:41:23 -04001358 find_module = _find_module_shim
Eric V. Smith984b11f2012-05-24 20:21:04 -04001359
1360 def find_loader(self, fullname):
1361 """Try to find a loader for the specified module, or the namespace
1362 package portions. Returns (loader, list-of-portions)."""
Eric V. Smithe51a3692012-06-24 19:13:55 -04001363 is_namespace = False
Brett Cannone9103d22009-03-12 22:37:06 +00001364 tail_module = fullname.rpartition('.')[2]
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001365 try:
1366 mtime = _os.stat(self.path).st_mtime
1367 except OSError:
1368 mtime = -1
Brett Cannonb46a1792012-02-27 18:15:42 -05001369 if mtime != self._path_mtime:
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001370 self._fill_cache()
1371 self._path_mtime = mtime
Antoine Pitroub5c793a2012-02-20 22:06:59 +01001372 # tail_module keeps the original casing, for __file__ and friends
1373 if _relax_case():
1374 cache = self._relaxed_path_cache
1375 cache_module = tail_module.lower()
1376 else:
1377 cache = self._path_cache
1378 cache_module = tail_module
Brett Cannon44590e42012-04-14 18:37:07 -04001379 # Check if the module is the name of a directory (and thus a package).
Antoine Pitroub5c793a2012-02-20 22:06:59 +01001380 if cache_module in cache:
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001381 base_path = _path_join(self.path, tail_module)
1382 if _path_isdir(base_path):
Brett Cannonac9f2f32012-08-10 13:47:54 -04001383 for suffix, loader in self._loaders:
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001384 init_filename = '__init__' + suffix
1385 full_path = _path_join(base_path, init_filename)
1386 if _path_isfile(full_path):
Eric V. Smith984b11f2012-05-24 20:21:04 -04001387 return (loader(fullname, full_path), [base_path])
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001388 else:
Eric V. Smithe51a3692012-06-24 19:13:55 -04001389 # A namespace package, return the path if we don't also
1390 # find a module in the next section.
1391 is_namespace = True
Brett Cannon44590e42012-04-14 18:37:07 -04001392 # Check for a file w/ a proper suffix exists.
Brett Cannonac9f2f32012-08-10 13:47:54 -04001393 for suffix, loader in self._loaders:
Brett Cannonf8ffec02013-04-01 13:10:51 -04001394 full_path = _path_join(self.path, tail_module + suffix)
1395 _verbose_message('trying {}'.format(full_path), verbosity=2)
Antoine Pitroub5c793a2012-02-20 22:06:59 +01001396 if cache_module + suffix in cache:
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001397 if _path_isfile(full_path):
Eric V. Smith984b11f2012-05-24 20:21:04 -04001398 return (loader(fullname, full_path), [])
Eric V. Smithe51a3692012-06-24 19:13:55 -04001399 if is_namespace:
Brett Cannonf8ffec02013-04-01 13:10:51 -04001400 _verbose_message('possible namespace for {}'.format(base_path))
Eric V. Smithe51a3692012-06-24 19:13:55 -04001401 return (None, [base_path])
Eric V. Smith984b11f2012-05-24 20:21:04 -04001402 return (None, [])
Brett Cannon61b14252010-07-03 21:48:25 +00001403
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001404 def _fill_cache(self):
1405 """Fill the cache of potential modules and packages for this directory."""
1406 path = self.path
Nick Coghlan48fec052012-08-20 13:18:15 +10001407 try:
1408 contents = _os.listdir(path)
Brett Cannona9976b32013-01-11 15:40:12 -05001409 except (FileNotFoundError, PermissionError, NotADirectoryError):
1410 # Directory has either been removed, turned into a file, or made
1411 # unreadable.
Nick Coghlan48fec052012-08-20 13:18:15 +10001412 contents = []
Antoine Pitroub5c793a2012-02-20 22:06:59 +01001413 # We store two cached versions, to handle runtime changes of the
1414 # PYTHONCASEOK environment variable.
Brett Cannon8ff6baf2012-04-20 12:53:14 -04001415 if not sys.platform.startswith('win'):
1416 self._path_cache = set(contents)
1417 else:
1418 # Windows users can import modules with case-insensitive file
1419 # suffixes (for legacy reasons). Make the suffix lowercase here
1420 # so it's done once instead of for every import. This is safe as
1421 # the specified suffixes to check against are always specified in a
1422 # case-sensitive manner.
1423 lower_suffix_contents = set()
1424 for item in contents:
1425 name, dot, suffix = item.partition('.')
1426 if dot:
1427 new_name = '{}.{}'.format(name, suffix.lower())
1428 else:
1429 new_name = name
1430 lower_suffix_contents.add(new_name)
1431 self._path_cache = lower_suffix_contents
Brett Cannon17098a52012-05-04 13:52:49 -04001432 if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
Serhiy Storchaka39e47f92013-02-25 15:40:33 +02001433 self._relaxed_path_cache = {fn.lower() for fn in contents}
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001434
Brett Cannon938d44d2012-04-22 19:58:33 -04001435 @classmethod
1436 def path_hook(cls, *loader_details):
1437 """A class method which returns a closure to use on sys.path_hook
1438 which will return an instance using the specified loaders and the path
1439 called on the closure.
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001440
Brett Cannon938d44d2012-04-22 19:58:33 -04001441 If the path called on the closure is not a directory, ImportError is
1442 raised.
Brett Cannon61b14252010-07-03 21:48:25 +00001443
Brett Cannon938d44d2012-04-22 19:58:33 -04001444 """
1445 def path_hook_for_FileFinder(path):
1446 """Path hook for importlib.machinery.FileFinder."""
1447 if not _path_isdir(path):
1448 raise ImportError("only directories are supported", path=path)
1449 return cls(path, *loader_details)
Brett Cannon61b14252010-07-03 21:48:25 +00001450
Brett Cannon938d44d2012-04-22 19:58:33 -04001451 return path_hook_for_FileFinder
Brett Cannon61b14252010-07-03 21:48:25 +00001452
Antoine Pitrou310f95b2012-06-23 02:12:56 +02001453 def __repr__(self):
Brett Cannon6072e0b2012-10-12 10:00:34 -04001454 return "FileFinder({!r})".format(self.path)
Brett Cannone9103d22009-03-12 22:37:06 +00001455
1456
Brett Cannonce43ddf2009-03-12 22:28:55 +00001457# Import itself ###############################################################
1458
Brett Cannone9103d22009-03-12 22:37:06 +00001459class _ImportLockContext:
1460
1461 """Context manager for the import lock."""
1462
1463 def __enter__(self):
1464 """Acquire the import lock."""
Brett Cannon6f44d662012-04-15 16:08:47 -04001465 _imp.acquire_lock()
Brett Cannone9103d22009-03-12 22:37:06 +00001466
1467 def __exit__(self, exc_type, exc_value, exc_traceback):
1468 """Release the import lock regardless of any raised exceptions."""
Brett Cannon6f44d662012-04-15 16:08:47 -04001469 _imp.release_lock()
Brett Cannone9103d22009-03-12 22:37:06 +00001470
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001471
Brett Cannon7fab6762012-02-16 13:43:41 -05001472def _resolve_name(name, package, level):
1473 """Resolve a relative module name to an absolute one."""
Philip Jenvey4b42ff62012-02-24 21:48:17 -08001474 bits = package.rsplit('.', level - 1)
Brett Cannon625cd232012-02-24 11:20:54 -05001475 if len(bits) < level:
1476 raise ValueError('attempted relative import beyond top-level package')
1477 base = bits[0]
Florent Xicluna79d79a02012-07-07 13:16:44 +02001478 return '{}.{}'.format(base, name) if name else base
Brett Cannon7fab6762012-02-16 13:43:41 -05001479
1480
1481def _find_module(name, path):
1482 """Find a module's loader."""
Brett Cannonce418b42012-04-27 14:01:58 -04001483 if not sys.meta_path:
1484 _warnings.warn('sys.meta_path is empty', ImportWarning)
1485 for finder in sys.meta_path:
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001486 with _ImportLockContext():
1487 loader = finder.find_module(name, path)
Brett Cannon7fab6762012-02-16 13:43:41 -05001488 if loader is not None:
1489 # The parent import may have already imported this module.
1490 if name not in sys.modules:
1491 return loader
1492 else:
1493 return sys.modules[name].__loader__
1494 else:
1495 return None
1496
1497
Brett Cannon7fab6762012-02-16 13:43:41 -05001498def _sanity_check(name, package, level):
1499 """Verify arguments are "sane"."""
Brett Cannon068915c2012-02-23 18:18:48 -05001500 if not isinstance(name, str):
Brett Cannon34d8e412012-02-22 18:33:05 -05001501 raise TypeError("module name must be str, not {}".format(type(name)))
1502 if level < 0:
1503 raise ValueError('level must be >= 0')
Brett Cannon7fab6762012-02-16 13:43:41 -05001504 if package:
Brett Cannon068915c2012-02-23 18:18:48 -05001505 if not isinstance(package, str):
Brett Cannonf5007782012-02-23 18:29:12 -05001506 raise TypeError("__package__ not set to a string")
Brett Cannon7fab6762012-02-16 13:43:41 -05001507 elif package not in sys.modules:
Florent Xicluna79d79a02012-07-07 13:16:44 +02001508 msg = ("Parent module {!r} not loaded, cannot perform relative "
Brett Cannon7fab6762012-02-16 13:43:41 -05001509 "import")
1510 raise SystemError(msg.format(package))
1511 if not name and level == 0:
1512 raise ValueError("Empty module name")
1513
1514
Brett Cannon34d8e412012-02-22 18:33:05 -05001515_ERR_MSG = 'No module named {!r}'
Brett Cannon7fab6762012-02-16 13:43:41 -05001516
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001517def _find_and_load_unlocked(name, import_):
Brett Cannon7fab6762012-02-16 13:43:41 -05001518 path = None
1519 parent = name.rpartition('.')[0]
1520 if parent:
1521 if parent not in sys.modules:
Nick Coghlan42c07662012-07-31 21:14:18 +10001522 _call_with_frames_removed(import_, parent)
Brett Cannon927d8742012-04-02 20:33:56 -04001523 # Crazy side-effects!
1524 if name in sys.modules:
1525 return sys.modules[name]
Brett Cannon7fab6762012-02-16 13:43:41 -05001526 # Backwards-compatibility; be nicer to skip the dict lookup.
1527 parent_module = sys.modules[parent]
1528 try:
1529 path = parent_module.__path__
1530 except AttributeError:
1531 msg = (_ERR_MSG + '; {} is not a package').format(name, parent)
Brett Cannonbbb66802012-04-12 21:09:01 -04001532 raise ImportError(msg, name=name)
Brett Cannon34d8e412012-02-22 18:33:05 -05001533 loader = _find_module(name, path)
1534 if loader is None:
Brett Cannon12c6bda2012-08-24 18:25:59 -04001535 exc = ImportError(_ERR_MSG.format(name), name=name)
1536 # TODO(brett): switch to a proper ModuleNotFound exception in Python
1537 # 3.4.
1538 exc._not_found = True
1539 raise exc
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001540 elif name not in sys.modules:
1541 # The parent import may have already imported this module.
1542 loader.load_module(name)
Brett Cannon17098a52012-05-04 13:52:49 -04001543 _verbose_message('import {!r} # {!r}', name, loader)
Benjamin Petersond76bc7a2012-04-18 10:55:43 -04001544 # Backwards-compatibility; be nicer to skip the dict lookup.
1545 module = sys.modules[name]
Brett Cannon34d8e412012-02-22 18:33:05 -05001546 if parent:
1547 # Set the module as an attribute on its parent.
1548 parent_module = sys.modules[parent]
1549 setattr(parent_module, name.rpartition('.')[2], module)
1550 # Set __package__ if the loader did not.
Florent Xicluna79d79a02012-07-07 13:16:44 +02001551 if getattr(module, '__package__', None) is None:
Brett Cannon34d8e412012-02-22 18:33:05 -05001552 try:
1553 module.__package__ = module.__name__
1554 if not hasattr(module, '__path__'):
1555 module.__package__ = module.__package__.rpartition('.')[0]
1556 except AttributeError:
1557 pass
Brett Cannonefad00d2012-04-27 17:27:14 -04001558 # Set loader if need be.
Brett Cannon4802bec2013-03-13 10:41:36 -07001559 if getattr(module, '__loader__', None) is None:
Brett Cannonefad00d2012-04-27 17:27:14 -04001560 try:
1561 module.__loader__ = loader
1562 except AttributeError:
1563 pass
Brett Cannon34d8e412012-02-22 18:33:05 -05001564 return module
Brett Cannon7fab6762012-02-16 13:43:41 -05001565
1566
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001567def _find_and_load(name, import_):
1568 """Find and load the module, and release the import lock."""
1569 try:
1570 lock = _get_module_lock(name)
1571 finally:
1572 _imp.release_lock()
1573 lock.acquire()
1574 try:
1575 return _find_and_load_unlocked(name, import_)
1576 finally:
1577 lock.release()
1578
1579
Brett Cannon7f9876c2009-02-06 02:47:33 +00001580def _gcd_import(name, package=None, level=0):
1581 """Import and return the module based on its name, the package the call is
1582 being made from, and the level adjustment.
1583
1584 This function represents the greatest common denominator of functionality
Eric V. Smith41698262011-03-14 10:56:33 -04001585 between import_module and __import__. This includes setting __package__ if
Brett Cannon2c318a12009-02-07 01:15:27 +00001586 the loader did not.
1587
Brett Cannon7f9876c2009-02-06 02:47:33 +00001588 """
Brett Cannon7fab6762012-02-16 13:43:41 -05001589 _sanity_check(name, package, level)
Brett Cannon7f9876c2009-02-06 02:47:33 +00001590 if level > 0:
Brett Cannon7fab6762012-02-16 13:43:41 -05001591 name = _resolve_name(name, package, level)
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001592 _imp.acquire_lock()
1593 if name not in sys.modules:
Brett Cannon34d8e412012-02-22 18:33:05 -05001594 return _find_and_load(name, _gcd_import)
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001595 module = sys.modules[name]
1596 if module is None:
1597 _imp.release_lock()
1598 message = ("import of {} halted; "
1599 "None in sys.modules".format(name))
1600 raise ImportError(message, name=name)
1601 _lock_unlock_module(name)
1602 return module
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001603
Brett Cannon4b03b682012-02-23 20:47:57 -05001604def _handle_fromlist(module, fromlist, import_):
Brett Cannon7fab6762012-02-16 13:43:41 -05001605 """Figure out what __import__ should return.
Brett Cannon2c318a12009-02-07 01:15:27 +00001606
Brett Cannon7fab6762012-02-16 13:43:41 -05001607 The import_ parameter is a callable which takes the name of module to
1608 import. It is required to decouple the function from assuming importlib's
1609 import implementation is desired.
Brett Cannon2c318a12009-02-07 01:15:27 +00001610
1611 """
Brett Cannon2c318a12009-02-07 01:15:27 +00001612 # The hell that is fromlist ...
Brett Cannon4b03b682012-02-23 20:47:57 -05001613 # If a package was imported, try to import stuff from fromlist.
1614 if hasattr(module, '__path__'):
Brett Cannon461c8132012-07-10 10:05:00 -04001615 if '*' in fromlist:
Brett Cannon4b03b682012-02-23 20:47:57 -05001616 fromlist = list(fromlist)
1617 fromlist.remove('*')
Brett Cannon461c8132012-07-10 10:05:00 -04001618 if hasattr(module, '__all__'):
1619 fromlist.extend(module.__all__)
Florent Xicluna79d79a02012-07-07 13:16:44 +02001620 for x in fromlist:
1621 if not hasattr(module, x):
Brett Cannona6ce4fd2012-10-10 19:03:46 -04001622 from_name = '{}.{}'.format(module.__name__, x)
Brett Cannon7385adc2012-08-17 13:21:16 -04001623 try:
Brett Cannona6ce4fd2012-10-10 19:03:46 -04001624 _call_with_frames_removed(import_, from_name)
Brett Cannon12c6bda2012-08-24 18:25:59 -04001625 except ImportError as exc:
Brett Cannon7385adc2012-08-17 13:21:16 -04001626 # Backwards-compatibility dictates we ignore failed
Brett Cannon12c6bda2012-08-24 18:25:59 -04001627 # imports triggered by fromlist for modules that don't
1628 # exist.
1629 # TODO(brett): In Python 3.4, have import raise
1630 # ModuleNotFound and catch that.
Brett Cannona6ce4fd2012-10-10 19:03:46 -04001631 if getattr(exc, '_not_found', False):
1632 if exc.name == from_name:
1633 continue
1634 raise
Brett Cannon4b03b682012-02-23 20:47:57 -05001635 return module
Brett Cannon354c26e2012-02-08 18:50:22 -05001636
1637
Brett Cannon7fab6762012-02-16 13:43:41 -05001638def _calc___package__(globals):
1639 """Calculate what __package__ should be.
1640
1641 __package__ is not guaranteed to be defined or could be set to None
1642 to represent that its proper value is unknown.
1643
1644 """
1645 package = globals.get('__package__')
1646 if package is None:
1647 package = globals['__name__']
1648 if '__path__' not in globals:
1649 package = package.rpartition('.')[0]
1650 return package
1651
1652
Martin v. Löwise3010a82012-07-28 21:33:05 +02001653def _get_supported_file_loaders():
1654 """Returns a list of file-based module loaders.
1655
1656 Each item is a tuple (loader, suffixes, allow_packages).
1657 """
Brett Cannonac9f2f32012-08-10 13:47:54 -04001658 extensions = ExtensionFileLoader, _imp.extension_suffixes()
1659 source = SourceFileLoader, SOURCE_SUFFIXES
1660 bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES
Martin v. Löwise3010a82012-07-28 21:33:05 +02001661 return [extensions, source, bytecode]
1662
1663
Brett Cannoncb4996a2012-08-06 16:34:44 -04001664def __import__(name, globals=None, locals=None, fromlist=(), level=0):
Brett Cannon7fab6762012-02-16 13:43:41 -05001665 """Import a module.
1666
1667 The 'globals' argument is used to infer where the import is occuring from
1668 to handle relative imports. The 'locals' argument is ignored. The
1669 'fromlist' argument specifies what should exist as attributes on the module
1670 being imported (e.g. ``from module import <fromlist>``). The 'level'
1671 argument represents the package location to import from in a relative
1672 import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
1673
1674 """
Brett Cannon7fab6762012-02-16 13:43:41 -05001675 if level == 0:
1676 module = _gcd_import(name)
1677 else:
Brett Cannoncb4996a2012-08-06 16:34:44 -04001678 globals_ = globals if globals is not None else {}
1679 package = _calc___package__(globals_)
Brett Cannon7fab6762012-02-16 13:43:41 -05001680 module = _gcd_import(name, package, level)
Brett Cannon4b03b682012-02-23 20:47:57 -05001681 if not fromlist:
1682 # Return up to the first dot in 'name'. This is complicated by the fact
1683 # that 'name' may be relative.
1684 if level == 0:
Antoine Pitrou6efa50a2012-05-07 21:41:59 +02001685 return _gcd_import(name.partition('.')[0])
Brett Cannon4b03b682012-02-23 20:47:57 -05001686 elif not name:
1687 return module
1688 else:
Brett Cannon8ed677d2012-09-28 16:41:39 -04001689 # Figure out where to slice the module's name up to the first dot
1690 # in 'name'.
Brett Cannon4b03b682012-02-23 20:47:57 -05001691 cut_off = len(name) - len(name.partition('.')[0])
Brett Cannon8ed677d2012-09-28 16:41:39 -04001692 # Slice end needs to be positive to alleviate need to special-case
1693 # when ``'.' not in name``.
Brett Cannon49f8d8b2012-04-14 21:50:00 -04001694 return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
Brett Cannon4b03b682012-02-23 20:47:57 -05001695 else:
1696 return _handle_fromlist(module, fromlist, _gcd_import)
Brett Cannon7fab6762012-02-16 13:43:41 -05001697
1698
Brett Cannon24117a72012-04-20 18:04:03 -04001699
Brett Cannon6f44d662012-04-15 16:08:47 -04001700def _setup(sys_module, _imp_module):
Brett Cannon354c26e2012-02-08 18:50:22 -05001701 """Setup importlib by importing needed built-in modules and injecting them
1702 into the global namespace.
1703
Brett Cannon6f44d662012-04-15 16:08:47 -04001704 As sys is needed for sys.modules access and _imp is needed to load built-in
Brett Cannon0568d6f2012-02-14 18:38:11 -05001705 modules, those two modules must be explicitly passed in.
Brett Cannon354c26e2012-02-08 18:50:22 -05001706
1707 """
Benjamin Petersonfeaa54f2012-09-25 11:22:59 -04001708 global _imp, sys, BYTECODE_SUFFIXES
Brett Cannon6f44d662012-04-15 16:08:47 -04001709 _imp = _imp_module
Brett Cannon354c26e2012-02-08 18:50:22 -05001710 sys = sys_module
1711
Benjamin Petersonfeaa54f2012-09-25 11:22:59 -04001712 if sys.flags.optimize:
1713 BYTECODE_SUFFIXES = OPTIMIZED_BYTECODE_SUFFIXES
1714 else:
1715 BYTECODE_SUFFIXES = DEBUG_BYTECODE_SUFFIXES
1716
Brett Cannon0ecd30b2013-02-01 14:04:12 -05001717 module_type = type(sys)
Brett Cannonda9cf0e2013-02-01 15:31:49 -05001718 for name, module in sys.modules.items():
Brett Cannon0ecd30b2013-02-01 14:04:12 -05001719 if isinstance(module, module_type):
1720 if not hasattr(module, '__loader__'):
Brett Cannonda9cf0e2013-02-01 15:31:49 -05001721 if name in sys.builtin_module_names:
1722 module.__loader__ = BuiltinImporter
1723 elif _imp.is_frozen(name):
1724 module.__loader__ = FrozenImporter
Brett Cannon354c26e2012-02-08 18:50:22 -05001725
1726 self_module = sys.modules[__name__]
1727 for builtin_name in ('_io', '_warnings', 'builtins', 'marshal'):
1728 if builtin_name not in sys.modules:
1729 builtin_module = BuiltinImporter.load_module(builtin_name)
1730 else:
1731 builtin_module = sys.modules[builtin_name]
1732 setattr(self_module, builtin_name, builtin_module)
1733
Jesus Cea4791a242012-10-05 03:15:39 +02001734 os_details = ('posix', ['/']), ('nt', ['\\', '/'])
Brett Cannoned672d62012-04-20 21:19:53 -04001735 for builtin_os, path_separators in os_details:
Brett Cannon5c903e62012-04-22 11:45:07 -04001736 # Assumption made in _path_join()
1737 assert all(len(sep) == 1 for sep in path_separators)
Brett Cannoned672d62012-04-20 21:19:53 -04001738 path_sep = path_separators[0]
Brett Cannon354c26e2012-02-08 18:50:22 -05001739 if builtin_os in sys.modules:
1740 os_module = sys.modules[builtin_os]
1741 break
1742 else:
1743 try:
1744 os_module = BuiltinImporter.load_module(builtin_os)
Brett Cannon354c26e2012-02-08 18:50:22 -05001745 break
1746 except ImportError:
1747 continue
1748 else:
1749 raise ImportError('importlib requires posix or nt')
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001750
1751 try:
1752 thread_module = BuiltinImporter.load_module('_thread')
1753 except ImportError:
1754 # Python was built without threads
1755 thread_module = None
1756 weakref_module = BuiltinImporter.load_module('_weakref')
1757
Martin v. Löwise3010a82012-07-28 21:33:05 +02001758 if builtin_os == 'nt':
1759 winreg_module = BuiltinImporter.load_module('winreg')
1760 setattr(self_module, '_winreg', winreg_module)
1761
Brett Cannon354c26e2012-02-08 18:50:22 -05001762 setattr(self_module, '_os', os_module)
Antoine Pitrouea3eb882012-05-17 18:55:59 +02001763 setattr(self_module, '_thread', thread_module)
1764 setattr(self_module, '_weakref', weakref_module)
Brett Cannon354c26e2012-02-08 18:50:22 -05001765 setattr(self_module, 'path_sep', path_sep)
Serhiy Storchaka39e47f92013-02-25 15:40:33 +02001766 setattr(self_module, 'path_separators', ''.join(path_separators))
Antoine Pitrouc541f8e2012-02-20 01:48:16 +01001767 # Constants
Antoine Pitroub67075b2012-02-20 13:52:47 +01001768 setattr(self_module, '_relax_case', _make_relax_case())
Brett Cannonac9f2f32012-08-10 13:47:54 -04001769 EXTENSION_SUFFIXES.extend(_imp.extension_suffixes())
Brett Cannona64faf02012-04-21 18:52:52 -04001770 if builtin_os == 'nt':
Brett Cannoncb66eb02012-05-11 12:58:42 -04001771 SOURCE_SUFFIXES.append('.pyw')
Brett Cannonac9f2f32012-08-10 13:47:54 -04001772 if '_d.pyd' in EXTENSION_SUFFIXES:
Nick Coghlanff794862012-08-02 21:45:24 +10001773 WindowsRegistryFinder.DEBUG_BUILD = True
Brett Cannonf2e86752012-02-17 09:46:48 -05001774
Brett Cannon0568d6f2012-02-14 18:38:11 -05001775
Brett Cannon6f44d662012-04-15 16:08:47 -04001776def _install(sys_module, _imp_module):
Brett Cannonfeccc092012-05-04 16:47:54 -04001777 """Install importlib as the implementation of import."""
Brett Cannon6f44d662012-04-15 16:08:47 -04001778 _setup(sys_module, _imp_module)
Martin v. Löwise3010a82012-07-28 21:33:05 +02001779 supported_loaders = _get_supported_file_loaders()
Brett Cannonaa936422012-04-27 15:30:58 -04001780 sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)])
Martin v. Löwise3010a82012-07-28 21:33:05 +02001781 sys.meta_path.append(BuiltinImporter)
1782 sys.meta_path.append(FrozenImporter)
1783 if _os.__name__ == 'nt':
Nick Coghlanff794862012-08-02 21:45:24 +10001784 sys.meta_path.append(WindowsRegistryFinder)
Martin v. Löwise3010a82012-07-28 21:33:05 +02001785 sys.meta_path.append(PathFinder)