blob: e94c1d2ddd1f6d34ba20c88203a703c843c88e31 [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"""
9
Brett Cannon7c9875c2009-03-04 01:10:09 +000010# Injected modules are '_warnings', 'imp', 'sys', 'marshal', 'errno', '_io',
11# and '_os' (a.k.a. 'posix', 'nt' or 'os2').
Brett Cannon23cbd8a2009-01-18 00:24:28 +000012# Injected attribute is path_sep.
13#
14# When editing this code be aware that code executed at import time CANNOT
15# reference any injected objects! This includes not only global code but also
16# anything specified at the class level.
17
18
Brett Cannonce43ddf2009-03-12 22:28:55 +000019# Bootstrap-related code ######################################################
20
Brett Cannon23cbd8a2009-01-18 00:24:28 +000021# XXX Could also expose Modules/getpath.c:joinpath()
22def _path_join(*args):
23 """Replacement for os.path.join."""
24 return path_sep.join(x[:-len(path_sep)] if x.endswith(path_sep) else x
25 for x in args)
26
27
28def _path_exists(path):
29 """Replacement for os.path.exists."""
30 try:
31 _os.stat(path)
32 except OSError:
33 return False
34 else:
35 return True
36
37
38def _path_is_mode_type(path, mode):
39 """Test whether the path is the specified mode type."""
40 try:
41 stat_info = _os.stat(path)
42 except OSError:
43 return False
44 return (stat_info.st_mode & 0o170000) == mode
45
46
47# XXX Could also expose Modules/getpath.c:isfile()
48def _path_isfile(path):
49 """Replacement for os.path.isfile."""
50 return _path_is_mode_type(path, 0o100000)
51
52
53# XXX Could also expose Modules/getpath.c:isdir()
54def _path_isdir(path):
55 """Replacement for os.path.isdir."""
56 return _path_is_mode_type(path, 0o040000)
57
58
59def _path_without_ext(path, ext_type):
60 """Replacement for os.path.splitext()[0]."""
Brett Cannon3eeaa0a2009-03-12 22:07:17 +000061 for suffix in _suffix_list(ext_type):
Brett Cannon23cbd8a2009-01-18 00:24:28 +000062 if path.endswith(suffix):
63 return path[:-len(suffix)]
64 else:
65 raise ValueError("path is not of the specified type")
66
67
68def _path_absolute(path):
69 """Replacement for os.path.abspath."""
70 if not path:
71 path = _os.getcwd()
72 try:
73 return _os._getfullpathname(path)
74 except AttributeError:
75 if path.startswith('/'):
76 return path
77 else:
78 return _path_join(_os.getcwd(), path)
79
80
Brett Cannon3eeaa0a2009-03-12 22:07:17 +000081class _closing:
Brett Cannon23cbd8a2009-01-18 00:24:28 +000082
83 """Simple replacement for contextlib.closing."""
84
85 def __init__(self, obj):
86 self.obj = obj
87
88 def __enter__(self):
89 return self.obj
90
91 def __exit__(self, *args):
92 self.obj.close()
93
94
Brett Cannon3eeaa0a2009-03-12 22:07:17 +000095def _wrap(new, old):
Brett Cannon51d8bfc2009-02-07 02:13:28 +000096 """Simple substitute for functools.wraps."""
97 for replace in ['__module__', '__name__', '__doc__']:
98 setattr(new, replace, getattr(old, replace))
99 new.__dict__.update(old.__dict__)
100
101
Brett Cannonce43ddf2009-03-12 22:28:55 +0000102# Finder/loader utility code ##################################################
103
Brett Cannon435aad82009-03-04 16:07:00 +0000104def set_package(fxn):
Brett Cannon06c9d962009-02-07 01:52:25 +0000105 """Set __package__ on the returned module."""
106 def wrapper(*args, **kwargs):
107 module = fxn(*args, **kwargs)
108 if not hasattr(module, '__package__') or module.__package__ is None:
109 module.__package__ = module.__name__
110 if not hasattr(module, '__path__'):
111 module.__package__ = module.__package__.rpartition('.')[0]
112 return module
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000113 _wrap(wrapper, fxn)
Brett Cannon06c9d962009-02-07 01:52:25 +0000114 return wrapper
115
116
Brett Cannon2cf03a82009-03-10 05:17:37 +0000117def set_loader(fxn):
118 """Set __loader__ on the returned module."""
119 def wrapper(self, *args, **kwargs):
120 module = fxn(self, *args, **kwargs)
121 if not hasattr(module, '__loader__'):
122 module.__loader__ = self
123 return module
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000124 _wrap(wrapper, fxn)
Brett Cannon2cf03a82009-03-10 05:17:37 +0000125 return wrapper
126
127
Brett Cannonce43ddf2009-03-12 22:28:55 +0000128def module_for_loader(fxn):
129 """Decorator to handle selecting the proper module for loaders.
130
Brett Cannon0e0d8a62009-03-15 00:00:19 +0000131 The decorated function is passed the module to use instead of the module
132 name. The module passed in to the function is either from sys.modules if
133 it already exists or is a new module which has __name__ set and is inserted
134 into sys.modules. If an exception is raised and the decorator created the
135 module it is subsequently removed from sys.modules.
Brett Cannonce43ddf2009-03-12 22:28:55 +0000136
Brett Cannon0e0d8a62009-03-15 00:00:19 +0000137 The decorator assumes that the decorated function takes the module name as
138 the second argument.
Brett Cannonce43ddf2009-03-12 22:28:55 +0000139
140 """
141 def decorated(self, fullname):
142 module = sys.modules.get(fullname)
143 is_reload = bool(module)
144 if not is_reload:
145 # This must be done before open() is called as the 'io' module
146 # implicitly imports 'locale' and would otherwise trigger an
147 # infinite loop.
148 module = imp.new_module(fullname)
149 sys.modules[fullname] = module
150 try:
151 return fxn(self, module)
152 except:
153 if not is_reload:
154 del sys.modules[fullname]
155 raise
156 _wrap(decorated, fxn)
157 return decorated
158
159
160def _check_name(method):
161 """Decorator to verify that the module being requested matches the one the
162 loader can handle.
163
164 The first argument (self) must define _name which the second argument is
165 comapred against. If the comparison fails then ImportError is raised.
166
167 """
168 def inner(self, name, *args, **kwargs):
169 if self._name != name:
170 raise ImportError("loader cannot handle %s" % name)
171 return method(self, name, *args, **kwargs)
172 _wrap(inner, method)
173 return inner
174
175
Brett Cannone9103d22009-03-12 22:37:06 +0000176def _suffix_list(suffix_type):
177 """Return a list of file suffixes based on the imp file type."""
178 return [suffix[0] for suffix in imp.get_suffixes()
179 if suffix[2] == suffix_type]
180
181
182# Loaders #####################################################################
Brett Cannonce43ddf2009-03-12 22:28:55 +0000183
Brett Cannon5abdc932009-01-22 22:43:07 +0000184class BuiltinImporter:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000185
Brett Cannon7aa21f72009-03-15 00:53:05 +0000186 """Meta path import for built-in modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000187
Brett Cannon7aa21f72009-03-15 00:53:05 +0000188 All methods are either class or static methods to avoid the need to
189 instantiate the class.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000190
191 """
192
Brett Cannon5abdc932009-01-22 22:43:07 +0000193 @classmethod
194 def find_module(cls, fullname, path=None):
Brett Cannon7aa21f72009-03-15 00:53:05 +0000195 """Find the built-in module.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000196
197 If 'path' is ever specified then the search is considered a failure.
198
199 """
200 if path is not None:
201 return None
Brett Cannon5abdc932009-01-22 22:43:07 +0000202 return cls if imp.is_builtin(fullname) else None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000203
Brett Cannon78246b62009-01-25 04:56:30 +0000204 @classmethod
Brett Cannon435aad82009-03-04 16:07:00 +0000205 @set_package
Brett Cannon2cf03a82009-03-10 05:17:37 +0000206 @set_loader
Brett Cannon78246b62009-01-25 04:56:30 +0000207 def load_module(cls, fullname):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000208 """Load a built-in module."""
209 if fullname not in sys.builtin_module_names:
210 raise ImportError("{0} is not a built-in module".format(fullname))
Brett Cannond2e7b332009-02-17 02:45:03 +0000211 is_reload = fullname in sys.modules
212 try:
213 return imp.init_builtin(fullname)
214 except:
215 if not is_reload and fullname in sys.modules:
216 del sys.modules[fullname]
217 raise
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000218
219
Brett Cannon5abdc932009-01-22 22:43:07 +0000220class FrozenImporter:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000221
Brett Cannon7aa21f72009-03-15 00:53:05 +0000222 """Meta path import for frozen modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000223
Brett Cannon7aa21f72009-03-15 00:53:05 +0000224 All methods are either class or static methods to avoid the need to
225 instantiate the class.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000226
Brett Cannon5abdc932009-01-22 22:43:07 +0000227 """
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000228
Brett Cannon5abdc932009-01-22 22:43:07 +0000229 @classmethod
230 def find_module(cls, fullname, path=None):
231 """Find a frozen module."""
232 return cls if imp.is_frozen(fullname) else None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000233
Brett Cannon5abdc932009-01-22 22:43:07 +0000234 @classmethod
Brett Cannon435aad82009-03-04 16:07:00 +0000235 @set_package
Brett Cannon2cf03a82009-03-10 05:17:37 +0000236 @set_loader
Brett Cannon5abdc932009-01-22 22:43:07 +0000237 def load_module(cls, fullname):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000238 """Load a frozen module."""
Brett Cannon5abdc932009-01-22 22:43:07 +0000239 if cls.find_module(fullname) is None:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000240 raise ImportError("{0} is not a frozen module".format(fullname))
Brett Cannond2e7b332009-02-17 02:45:03 +0000241 is_reload = fullname in sys.modules
242 try:
243 return imp.init_frozen(fullname)
244 except:
245 if not is_reload and fullname in sys.modules:
246 del sys.modules[fullname]
247 raise
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000248
249
Brett Cannon91cf8822009-02-21 05:41:15 +0000250class PyLoader:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000251
Brett Cannon7aa21f72009-03-15 00:53:05 +0000252 """Loader base class for Python source code.
Brett Cannon91cf8822009-02-21 05:41:15 +0000253
Brett Cannon7aa21f72009-03-15 00:53:05 +0000254 Subclasses need to implement the methods:
255
256 - source_path
257 - get_data
258 - is_package
Brett Cannon91cf8822009-02-21 05:41:15 +0000259
260 """
261
262 @module_for_loader
263 def load_module(self, module):
264 """Load a source module."""
Brett Cannon1014d422009-03-08 20:53:50 +0000265 return self._load_module(module)
Brett Cannon91cf8822009-02-21 05:41:15 +0000266
267 def _load_module(self, module):
268 """Initialize a module from source."""
269 name = module.__name__
Brett Cannon91cf8822009-02-21 05:41:15 +0000270 code_object = self.get_code(module.__name__)
Brett Cannon1014d422009-03-08 20:53:50 +0000271 # __file__ may have been set by the caller, e.g. bytecode path.
Brett Cannon91cf8822009-02-21 05:41:15 +0000272 if not hasattr(module, '__file__'):
Brett Cannon1014d422009-03-08 20:53:50 +0000273 module.__file__ = self.source_path(name)
Brett Cannon91cf8822009-02-21 05:41:15 +0000274 if self.is_package(name):
275 module.__path__ = [module.__file__.rsplit(path_sep, 1)[0]]
276 module.__package__ = module.__name__
277 if not hasattr(module, '__path__'):
278 module.__package__ = module.__package__.rpartition('.')[0]
Brett Cannon1014d422009-03-08 20:53:50 +0000279 module.__loader__ = self
Brett Cannon91cf8822009-02-21 05:41:15 +0000280 exec(code_object, module.__dict__)
281 return module
282
283 def get_code(self, fullname):
284 """Get a code object from source."""
285 source_path = self.source_path(fullname)
Brett Cannon1014d422009-03-08 20:53:50 +0000286 if source_path is None:
287 message = "a source path must exist to load {0}".format(fullname)
288 raise ImportError(message)
Brett Cannon91cf8822009-02-21 05:41:15 +0000289 source = self.get_data(source_path)
290 # Convert to universal newlines.
291 line_endings = b'\n'
292 for index, c in enumerate(source):
293 if c == ord(b'\n'):
294 break
295 elif c == ord(b'\r'):
296 line_endings = b'\r'
297 try:
298 if source[index+1] == ord(b'\n'):
299 line_endings += b'\n'
300 except IndexError:
301 pass
302 break
303 if line_endings != b'\n':
304 source = source.replace(line_endings, b'\n')
305 return compile(source, source_path, 'exec', dont_inherit=True)
306
Brett Cannond43b30b2009-03-10 03:29:23 +0000307 # Never use in implementing import! Imports code within the method.
308 def get_source(self, fullname):
309 """Return the source code for a module.
310
311 self.source_path() and self.get_data() are used to implement this
312 method.
313
314 """
315 path = self.source_path(fullname)
316 if path is None:
317 return None
318 try:
319 source_bytes = self.get_data(path)
320 except IOError:
321 return ImportError("source not available through get_data()")
322 import io
323 import tokenize
324 encoding = tokenize.detect_encoding(io.BytesIO(source_bytes).readline)
325 return source_bytes.decode(encoding[0])
326
Brett Cannon91cf8822009-02-21 05:41:15 +0000327
328class PyPycLoader(PyLoader):
329
330 """Loader base class for Python source and bytecode.
331
332 Requires implementing the methods needed for PyLoader as well as
Brett Cannon94aaf9e2009-02-21 23:12:24 +0000333 source_mtime, bytecode_path, and write_bytecode.
Brett Cannon91cf8822009-02-21 05:41:15 +0000334
335 """
336
337 @module_for_loader
338 def load_module(self, module):
339 """Load a module from source or bytecode."""
340 name = module.__name__
Brett Cannon2a922ed2009-03-09 03:35:50 +0000341 source_path = self.source_path(name)
342 bytecode_path = self.bytecode_path(name)
Brett Cannon29dff8a2009-03-09 00:14:37 +0000343 # get_code can worry about no viable paths existing.
344 module.__file__ = source_path or bytecode_path
Brett Cannon91cf8822009-02-21 05:41:15 +0000345 return self._load_module(module)
346
347 def get_code(self, fullname):
348 """Get a code object from source or bytecode."""
349 # XXX Care enough to make sure this call does not happen if the magic
350 # number is bad?
351 source_timestamp = self.source_mtime(fullname)
352 # Try to use bytecode if it is available.
353 bytecode_path = self.bytecode_path(fullname)
354 if bytecode_path:
355 data = self.get_data(bytecode_path)
356 magic = data[:4]
357 pyc_timestamp = marshal._r_long(data[4:8])
358 bytecode = data[8:]
359 try:
360 # Verify that the magic number is valid.
361 if imp.get_magic() != magic:
362 raise ImportError("bad magic number")
363 # Verify that the bytecode is not stale (only matters when
364 # there is source to fall back on.
365 if source_timestamp:
366 if pyc_timestamp < source_timestamp:
367 raise ImportError("bytecode is stale")
368 except ImportError:
369 # If source is available give it a shot.
370 if source_timestamp is not None:
371 pass
372 else:
373 raise
374 else:
375 # Bytecode seems fine, so try to use it.
376 # XXX If the bytecode is ill-formed, would it be beneficial to
377 # try for using source if available and issue a warning?
378 return marshal.loads(bytecode)
379 elif source_timestamp is None:
380 raise ImportError("no source or bytecode available to create code "
381 "object for {0!r}".format(fullname))
382 # Use the source.
383 code_object = super().get_code(fullname)
384 # Generate bytecode and write it out.
385 if not sys.dont_write_bytecode:
386 data = bytearray(imp.get_magic())
387 data.extend(marshal._w_long(source_timestamp))
388 data.extend(marshal.dumps(code_object))
389 self.write_bytecode(fullname, data)
390 return code_object
391
392
Brett Cannonf87e04d2009-03-12 22:47:53 +0000393class _PyFileLoader(PyLoader):
Brett Cannon91cf8822009-02-21 05:41:15 +0000394
395 """Load a Python source file."""
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000396
397 def __init__(self, name, path, is_pkg):
398 self._name = name
399 self._is_pkg = is_pkg
400 # Figure out the base path based on whether it was source or bytecode
401 # that was found.
402 try:
403 self._base_path = _path_without_ext(path, imp.PY_SOURCE)
404 except ValueError:
405 self._base_path = _path_without_ext(path, imp.PY_COMPILED)
406
407 def _find_path(self, ext_type):
408 """Find a path from the base path and the specified extension type that
409 exists, returning None if one is not found."""
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000410 for suffix in _suffix_list(ext_type):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000411 path = self._base_path + suffix
412 if _path_exists(path):
413 return path
414 else:
415 return None
416
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000417 @_check_name
Brett Cannon51c50262009-02-01 05:33:17 +0000418 def source_path(self, fullname):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000419 """Return the path to an existing source file for the module, or None
420 if one cannot be found."""
421 # Not a property so that it is easy to override.
422 return self._find_path(imp.PY_SOURCE)
423
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000424 @_check_name
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000425 def get_source(self, fullname):
426 """Return the source for the module as a string.
427
428 Return None if the source is not available. Raise ImportError if the
429 laoder cannot handle the specified module.
430
431 """
Brett Cannon51c50262009-02-01 05:33:17 +0000432 source_path = self._source_path(name)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000433 if source_path is None:
434 return None
435 import tokenize
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000436 with _closing(_io.FileIO(source_path, 'r')) as file: # Assuming bytes.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000437 encoding, lines = tokenize.detect_encoding(file.readline)
438 # XXX Will fail when passed to compile() if the encoding is
439 # anything other than UTF-8.
440 return open(source_path, encoding=encoding).read()
441
Brett Cannon91cf8822009-02-21 05:41:15 +0000442
443 def get_data(self, path):
444 """Return the data from path as raw bytes."""
Brett Cannon7c9875c2009-03-04 01:10:09 +0000445 return _io.FileIO(path, 'r').read() # Assuming bytes.
Brett Cannon91cf8822009-02-21 05:41:15 +0000446
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000447 @_check_name
Brett Cannon91cf8822009-02-21 05:41:15 +0000448 def is_package(self, fullname):
449 """Return a boolean based on whether the module is a package.
450
451 Raises ImportError (like get_source) if the loader cannot handle the
452 package.
453
454 """
455 return self._is_pkg
456
457
Brett Cannonf87e04d2009-03-12 22:47:53 +0000458class _PyPycFileLoader(PyPycLoader, _PyFileLoader):
Brett Cannon91cf8822009-02-21 05:41:15 +0000459
460 """Load a module from a source or bytecode file."""
461
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000462 @_check_name
Brett Cannon94aaf9e2009-02-21 23:12:24 +0000463 def source_mtime(self, name):
464 """Return the modification time of the source for the specified
465 module."""
466 source_path = self.source_path(name)
467 if not source_path:
468 return None
469 return int(_os.stat(source_path).st_mtime)
470
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000471 @_check_name
Brett Cannon91cf8822009-02-21 05:41:15 +0000472 def bytecode_path(self, fullname):
473 """Return the path to a bytecode file, or None if one does not
474 exist."""
475 # Not a property for easy overriding.
476 return self._find_path(imp.PY_COMPILED)
477
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000478 @_check_name
Brett Cannon776e7012009-02-01 06:07:57 +0000479 def write_bytecode(self, name, data):
480 """Write out 'data' for the specified module, returning a boolean
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000481 signifying if the write-out actually occurred.
482
483 Raises ImportError (just like get_source) if the specified module
484 cannot be handled by the loader.
485
486 """
Brett Cannon51c50262009-02-01 05:33:17 +0000487 bytecode_path = self.bytecode_path(name)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000488 if not bytecode_path:
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000489 bytecode_path = self._base_path + _suffix_list(imp.PY_COMPILED)[0]
Brett Cannon7c9875c2009-03-04 01:10:09 +0000490 file = _io.FileIO(bytecode_path, 'w') # Assuming bytes.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000491 try:
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000492 with _closing(file) as bytecode_file:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000493 bytecode_file.write(data)
494 return True
495 except IOError as exc:
496 if exc.errno == errno.EACCES:
497 return False
498 else:
499 raise
500
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000501
Brett Cannone9103d22009-03-12 22:37:06 +0000502class _ExtensionFileLoader:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000503
Brett Cannone9103d22009-03-12 22:37:06 +0000504 """Loader for extension modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000505
Brett Cannone9103d22009-03-12 22:37:06 +0000506 The constructor is designed to work with FileFinder.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000507
508 """
509
Brett Cannone9103d22009-03-12 22:37:06 +0000510 def __init__(self, name, path, is_pkg):
511 """Initialize the loader.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000512
Brett Cannone9103d22009-03-12 22:37:06 +0000513 If is_pkg is True then an exception is raised as extension modules
514 cannot be the __init__ module for an extension module.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000515
516 """
Brett Cannone9103d22009-03-12 22:37:06 +0000517 self._name = name
518 self._path = path
519 if is_pkg:
520 raise ValueError("extension modules cannot be packages")
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000521
Brett Cannone9103d22009-03-12 22:37:06 +0000522 @_check_name
523 @set_package
524 @set_loader
525 def load_module(self, fullname):
526 """Load an extension module."""
527 is_reload = fullname in sys.modules
528 try:
529 return imp.load_dynamic(fullname, self._path)
530 except:
531 if not is_reload and fullname in sys.modules:
532 del sys.modules[fullname]
533 raise
534
535 @_check_name
536 def is_package(self, fullname):
537 """Return False as an extension module can never be a package."""
538 return False
539
540 @_check_name
541 def get_code(self, fullname):
542 """Return None as an extension module cannot create a code object."""
543 return None
544
545 @_check_name
546 def get_source(self, fullname):
547 """Return None as extension modules have no source code."""
548 return None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000549
550
Brett Cannone9103d22009-03-12 22:37:06 +0000551# Finders #####################################################################
Brett Cannon4afab6b2009-02-21 03:31:35 +0000552
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000553class PathFinder:
Brett Cannon1d376682009-02-02 19:19:36 +0000554
555 """Meta path finder for sys.(path|path_hooks|path_importer_cache)."""
556
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000557 @classmethod
Brett Cannon32732e32009-02-15 05:48:13 +0000558 def _path_hooks(cls, path, hooks=None):
559 """Search sequence of hooks for a finder for 'path'.
Brett Cannon1d376682009-02-02 19:19:36 +0000560
Brett Cannon32732e32009-02-15 05:48:13 +0000561 If 'hooks' is false then use sys.path_hooks.
Brett Cannon1d376682009-02-02 19:19:36 +0000562
563 """
Brett Cannon32732e32009-02-15 05:48:13 +0000564 if not hooks:
565 hooks = sys.path_hooks
566 for hook in hooks:
Brett Cannon1d376682009-02-02 19:19:36 +0000567 try:
568 return hook(path)
569 except ImportError:
570 continue
571 else:
Brett Cannon32732e32009-02-15 05:48:13 +0000572 raise ImportError("no path hook found for {0}".format(path))
Brett Cannon1d376682009-02-02 19:19:36 +0000573
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000574 @classmethod
Brett Cannon32732e32009-02-15 05:48:13 +0000575 def _path_importer_cache(cls, path, default=None):
Brett Cannon1d376682009-02-02 19:19:36 +0000576 """Get the finder for the path from sys.path_importer_cache.
577
578 If the path is not in the cache, find the appropriate finder and cache
579 it. If None is cached, get the default finder and cache that
580 (if applicable).
581
582 Because of NullImporter, some finder should be returned. The only
583 explicit fail case is if None is cached but the path cannot be used for
584 the default hook, for which ImportError is raised.
585
586 """
587 try:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000588 finder = sys.path_importer_cache[path]
Brett Cannon1d376682009-02-02 19:19:36 +0000589 except KeyError:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000590 finder = cls._path_hooks(path)
Brett Cannon1d376682009-02-02 19:19:36 +0000591 sys.path_importer_cache[path] = finder
592 else:
Brett Cannon32732e32009-02-15 05:48:13 +0000593 if finder is None and default:
Brett Cannon1d376682009-02-02 19:19:36 +0000594 # Raises ImportError on failure.
Brett Cannon32732e32009-02-15 05:48:13 +0000595 finder = default(path)
Brett Cannon1d376682009-02-02 19:19:36 +0000596 sys.path_importer_cache[path] = finder
597 return finder
598
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000599 @classmethod
600 def find_module(cls, fullname, path=None):
Brett Cannon7aa21f72009-03-15 00:53:05 +0000601 """Find the module on sys.path or 'path' based on sys.path_hooks and
602 sys.path_importer_cache."""
Brett Cannon1d376682009-02-02 19:19:36 +0000603 if not path:
604 path = sys.path
605 for entry in path:
606 try:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000607 finder = cls._path_importer_cache(entry)
Brett Cannon1d376682009-02-02 19:19:36 +0000608 except ImportError:
609 continue
610 loader = finder.find_module(fullname)
611 if loader:
612 return loader
613 else:
614 return None
615
616
Brett Cannone9103d22009-03-12 22:37:06 +0000617class _ChainedFinder:
618
619 """Finder that sequentially calls other finders."""
620
621 def __init__(self, *finders):
622 self._finders = finders
623
624 def find_module(self, fullname, path=None):
625 for finder in self._finders:
626 result = finder.find_module(fullname, path)
627 if result:
628 return result
629 else:
630 return None
631
632
Brett Cannonf87e04d2009-03-12 22:47:53 +0000633class _FileFinder:
Brett Cannone9103d22009-03-12 22:37:06 +0000634
635 """Base class for file finders.
636
637 Subclasses are expected to define the following attributes:
638
639 * _suffixes
640 Sequence of file suffixes whose order will be followed.
641
642 * _possible_package
643 True if importer should check for packages.
644
645 * _loader
646 A callable that takes the module name, a file path, and whether
647 the path points to a package and returns a loader for the module
648 found at that path.
649
650 """
651
652 def __init__(self, path_entry):
653 """Initialize an importer for the passed-in sys.path entry (which is
654 assumed to have already been verified as an existing directory).
655
656 Can be used as an entry on sys.path_hook.
657
658 """
659 absolute_path = _path_absolute(path_entry)
660 if not _path_isdir(absolute_path):
661 raise ImportError("only directories are supported")
662 self._path_entry = absolute_path
663
664 def find_module(self, fullname, path=None):
665 tail_module = fullname.rpartition('.')[2]
666 package_directory = None
667 if self._possible_package:
668 for ext in self._suffixes:
669 package_directory = _path_join(self._path_entry, tail_module)
670 init_filename = '__init__' + ext
671 package_init = _path_join(package_directory, init_filename)
672 if (_path_isfile(package_init) and
673 _case_ok(self._path_entry, tail_module) and
674 _case_ok(package_directory, init_filename)):
675 return self._loader(fullname, package_init, True)
676 for ext in self._suffixes:
677 file_name = tail_module + ext
678 file_path = _path_join(self._path_entry, file_name)
679 if (_path_isfile(file_path) and
680 _case_ok(self._path_entry, file_name)):
681 return self._loader(fullname, file_path, False)
682 else:
683 # Raise a warning if it matches a directory w/o an __init__ file.
684 if (package_directory is not None and
685 _path_isdir(package_directory) and
686 _case_ok(self._path_entry, tail_module)):
687 _warnings.warn("Not importing directory %s: missing __init__"
688 % package_directory, ImportWarning)
689 return None
690
691
Brett Cannonf87e04d2009-03-12 22:47:53 +0000692class _PyFileFinder(_FileFinder):
Brett Cannone9103d22009-03-12 22:37:06 +0000693
694 """Importer for source/bytecode files."""
695
696 _possible_package = True
Brett Cannonf87e04d2009-03-12 22:47:53 +0000697 _loader = _PyFileLoader
Brett Cannone9103d22009-03-12 22:37:06 +0000698
699 def __init__(self, path_entry):
700 # Lack of imp during class creation means _suffixes is set here.
701 # Make sure that Python source files are listed first! Needed for an
702 # optimization by the loader.
703 self._suffixes = _suffix_list(imp.PY_SOURCE)
704 super().__init__(path_entry)
705
706
Brett Cannonf87e04d2009-03-12 22:47:53 +0000707class _PyPycFileFinder(_PyFileFinder):
Brett Cannone9103d22009-03-12 22:37:06 +0000708
709 """Finder for source and bytecode files."""
710
Brett Cannonf87e04d2009-03-12 22:47:53 +0000711 _loader = _PyPycFileLoader
Brett Cannone9103d22009-03-12 22:37:06 +0000712
713 def __init__(self, path_entry):
714 super().__init__(path_entry)
715 self._suffixes += _suffix_list(imp.PY_COMPILED)
716
717
718
719
Brett Cannonf87e04d2009-03-12 22:47:53 +0000720class _ExtensionFileFinder(_FileFinder):
Brett Cannone9103d22009-03-12 22:37:06 +0000721
722 """Importer for extension files."""
723
724 _possible_package = False
725 _loader = _ExtensionFileLoader
726
727 def __init__(self, path_entry):
728 # Assigning to _suffixes here instead of at the class level because
729 # imp is not imported at the time of class creation.
730 self._suffixes = _suffix_list(imp.C_EXTENSION)
731 super().__init__(path_entry)
732
733
Brett Cannonce43ddf2009-03-12 22:28:55 +0000734# Import itself ###############################################################
735
Brett Cannone9103d22009-03-12 22:37:06 +0000736def _chained_path_hook(*path_hooks):
737 """Create a closure which sequentially checks path hooks to see which ones
738 (if any) can work with a path."""
739 def path_hook(entry):
740 """Check to see if 'entry' matches any of the enclosed path hooks."""
741 finders = []
742 for hook in path_hooks:
743 try:
744 finder = hook(entry)
745 except ImportError:
746 continue
747 else:
748 finders.append(finder)
749 if not finders:
750 raise ImportError("no finder found")
751 else:
752 return _ChainedFinder(*finders)
Brett Cannonce43ddf2009-03-12 22:28:55 +0000753
Brett Cannone9103d22009-03-12 22:37:06 +0000754 return path_hook
Brett Cannonce43ddf2009-03-12 22:28:55 +0000755
756
Brett Cannonf87e04d2009-03-12 22:47:53 +0000757_DEFAULT_PATH_HOOK = _chained_path_hook(_ExtensionFileFinder, _PyPycFileFinder)
Brett Cannon2dee5972009-02-21 03:15:37 +0000758
Brett Cannon32732e32009-02-15 05:48:13 +0000759class _DefaultPathFinder(PathFinder):
760
761 """Subclass of PathFinder that implements implicit semantics for
762 __import__."""
763
Brett Cannon32732e32009-02-15 05:48:13 +0000764 @classmethod
765 def _path_hooks(cls, path):
766 """Search sys.path_hooks as well as implicit path hooks."""
767 try:
768 return super()._path_hooks(path)
769 except ImportError:
Brett Cannon2dee5972009-02-21 03:15:37 +0000770 implicit_hooks = [_DEFAULT_PATH_HOOK, imp.NullImporter]
Brett Cannon32732e32009-02-15 05:48:13 +0000771 return super()._path_hooks(path, implicit_hooks)
772
773 @classmethod
774 def _path_importer_cache(cls, path):
775 """Use the default path hook when None is stored in
776 sys.path_importer_cache."""
Brett Cannon2dee5972009-02-21 03:15:37 +0000777 return super()._path_importer_cache(path, _DEFAULT_PATH_HOOK)
Brett Cannon32732e32009-02-15 05:48:13 +0000778
779
Brett Cannone9103d22009-03-12 22:37:06 +0000780class _ImportLockContext:
781
782 """Context manager for the import lock."""
783
784 def __enter__(self):
785 """Acquire the import lock."""
786 imp.acquire_lock()
787
788 def __exit__(self, exc_type, exc_value, exc_traceback):
789 """Release the import lock regardless of any raised exceptions."""
790 imp.release_lock()
791
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000792
Brett Cannon32732e32009-02-15 05:48:13 +0000793_IMPLICIT_META_PATH = [BuiltinImporter, FrozenImporter, _DefaultPathFinder]
794
Brett Cannon7f9876c2009-02-06 02:47:33 +0000795def _gcd_import(name, package=None, level=0):
796 """Import and return the module based on its name, the package the call is
797 being made from, and the level adjustment.
798
799 This function represents the greatest common denominator of functionality
Brett Cannon2c318a12009-02-07 01:15:27 +0000800 between import_module and __import__. This includes settting __package__ if
801 the loader did not.
802
Brett Cannon7f9876c2009-02-06 02:47:33 +0000803 """
Brett Cannon2c318a12009-02-07 01:15:27 +0000804 if package:
805 if not hasattr(package, 'rindex'):
806 raise ValueError("__package__ not set to a string")
807 elif package not in sys.modules:
808 msg = ("Parent module {0!r} not loaded, cannot perform relative "
809 "import")
810 raise SystemError(msg.format(package))
811 if not name and level == 0:
812 raise ValueError("Empty module name")
Brett Cannon7f9876c2009-02-06 02:47:33 +0000813 if level > 0:
Brett Cannon2c318a12009-02-07 01:15:27 +0000814 dot = len(package)
Brett Cannon7f9876c2009-02-06 02:47:33 +0000815 for x in range(level, 1, -1):
816 try:
817 dot = package.rindex('.', 0, dot)
Brett Cannon7f9876c2009-02-06 02:47:33 +0000818 except ValueError:
Brett Cannon2c318a12009-02-07 01:15:27 +0000819 raise ValueError("attempted relative import beyond "
820 "top-level package")
821 if name:
822 name = "{0}.{1}".format(package[:dot], name)
823 else:
824 name = package[:dot]
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000825 with _ImportLockContext():
Brett Cannon7f9876c2009-02-06 02:47:33 +0000826 try:
827 return sys.modules[name]
828 except KeyError:
829 pass
830 parent = name.rpartition('.')[0]
831 path = None
832 if parent:
833 if parent not in sys.modules:
Brett Cannon2c318a12009-02-07 01:15:27 +0000834 _gcd_import(parent)
835 # Backwards-compatibility; be nicer to skip the dict lookup.
836 parent_module = sys.modules[parent]
Brett Cannon7f9876c2009-02-06 02:47:33 +0000837 path = parent_module.__path__
Brett Cannon32732e32009-02-15 05:48:13 +0000838 meta_path = sys.meta_path + _IMPLICIT_META_PATH
Brett Cannon2c318a12009-02-07 01:15:27 +0000839 for finder in meta_path:
Brett Cannon7f9876c2009-02-06 02:47:33 +0000840 loader = finder.find_module(name, path)
Brett Cannon2c318a12009-02-07 01:15:27 +0000841 if loader is not None:
842 loader.load_module(name)
843 break
Brett Cannon7f9876c2009-02-06 02:47:33 +0000844 else:
845 raise ImportError("No module named {0}".format(name))
Brett Cannon2c318a12009-02-07 01:15:27 +0000846 # Backwards-compatibility; be nicer to skip the dict lookup.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000847 module = sys.modules[name]
848 if parent:
Brett Cannon2c318a12009-02-07 01:15:27 +0000849 # Set the module as an attribute on its parent.
850 setattr(parent_module, name.rpartition('.')[2], module)
851 # Set __package__ if the loader did not.
852 if not hasattr(module, '__package__') or module.__package__ is None:
853 # Watch out for what comes out of sys.modules to not be a module,
854 # e.g. an int.
855 try:
856 module.__package__ = module.__name__
857 if not hasattr(module, '__path__'):
858 module.__package__ = module.__package__.rpartition('.')[0]
859 except AttributeError:
860 pass
861 return module
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000862
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000863
Brett Cannon7aa21f72009-03-15 00:53:05 +0000864def __import__(name, globals={}, locals={}, fromlist=[], level=0):
Brett Cannon2c318a12009-02-07 01:15:27 +0000865 """Import a module.
866
867 The 'globals' argument is used to infer where the import is occuring from
868 to handle relative imports. The 'locals' argument is ignored. The
869 'fromlist' argument specifies what should exist as attributes on the module
870 being imported (e.g. ``from module import <fromlist>``). The 'level'
871 argument represents the package location to import from in a relative
872 import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
873
874 """
875 if level == 0:
876 module = _gcd_import(name)
877 else:
878 # __package__ is not guaranteed to be defined.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000879 try:
Brett Cannon2c318a12009-02-07 01:15:27 +0000880 package = globals['__package__']
881 except KeyError:
882 package = globals['__name__']
883 if '__path__' not in globals:
884 package = package.rpartition('.')[0]
885 module = _gcd_import(name, package, level)
886 # The hell that is fromlist ...
887 if not fromlist:
888 # Return up to the first dot in 'name'. This is complicated by the fact
889 # that 'name' may be relative.
890 if level == 0:
891 return sys.modules[name.partition('.')[0]]
892 elif not name:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000893 return module
Brett Cannon2c318a12009-02-07 01:15:27 +0000894 else:
895 cut_off = len(name) - len(name.partition('.')[0])
896 return sys.modules[module.__name__[:-cut_off]]
897 else:
898 # If a package was imported, try to import stuff from fromlist.
899 if hasattr(module, '__path__'):
900 if '*' in fromlist and hasattr(module, '__all__'):
901 fromlist.remove('*')
902 fromlist.extend(module.__all__)
903 for x in (y for y in fromlist if not hasattr(module,y)):
904 try:
905 _gcd_import('{0}.{1}'.format(module.__name__, x))
906 except ImportError:
907 pass
908 return module