blob: 04d9bff344cf15da14090403188a6d9031b001b6 [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
Brett Cannon61b14252010-07-03 21:48:25 +000025 for x in args if x)
Brett Cannon23cbd8a2009-01-18 00:24:28 +000026
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."""
Brett Cannon61b14252010-07-03 21:48:25 +000056 if not path:
57 path = _os.getcwd()
Brett Cannon23cbd8a2009-01-18 00:24:28 +000058 return _path_is_mode_type(path, 0o040000)
59
60
61def _path_without_ext(path, ext_type):
62 """Replacement for os.path.splitext()[0]."""
Brett Cannon3eeaa0a2009-03-12 22:07:17 +000063 for suffix in _suffix_list(ext_type):
Brett Cannon23cbd8a2009-01-18 00:24:28 +000064 if path.endswith(suffix):
65 return path[:-len(suffix)]
66 else:
67 raise ValueError("path is not of the specified type")
68
69
70def _path_absolute(path):
71 """Replacement for os.path.abspath."""
72 if not path:
73 path = _os.getcwd()
74 try:
75 return _os._getfullpathname(path)
76 except AttributeError:
77 if path.startswith('/'):
78 return path
79 else:
80 return _path_join(_os.getcwd(), path)
81
82
Brett Cannon3eeaa0a2009-03-12 22:07:17 +000083class _closing:
Brett Cannon23cbd8a2009-01-18 00:24:28 +000084
85 """Simple replacement for contextlib.closing."""
86
87 def __init__(self, obj):
88 self.obj = obj
89
90 def __enter__(self):
91 return self.obj
92
93 def __exit__(self, *args):
94 self.obj.close()
95
96
Brett Cannon3eeaa0a2009-03-12 22:07:17 +000097def _wrap(new, old):
Brett Cannon51d8bfc2009-02-07 02:13:28 +000098 """Simple substitute for functools.wraps."""
99 for replace in ['__module__', '__name__', '__doc__']:
100 setattr(new, replace, getattr(old, replace))
101 new.__dict__.update(old.__dict__)
102
103
Brett Cannon61b14252010-07-03 21:48:25 +0000104code_type = type(_wrap.__code__)
105
Brett Cannonce43ddf2009-03-12 22:28:55 +0000106# Finder/loader utility code ##################################################
107
Brett Cannon435aad82009-03-04 16:07:00 +0000108def set_package(fxn):
Brett Cannon06c9d962009-02-07 01:52:25 +0000109 """Set __package__ on the returned module."""
110 def wrapper(*args, **kwargs):
111 module = fxn(*args, **kwargs)
112 if not hasattr(module, '__package__') or module.__package__ is None:
113 module.__package__ = module.__name__
114 if not hasattr(module, '__path__'):
115 module.__package__ = module.__package__.rpartition('.')[0]
116 return module
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000117 _wrap(wrapper, fxn)
Brett Cannon06c9d962009-02-07 01:52:25 +0000118 return wrapper
119
120
Brett Cannon2cf03a82009-03-10 05:17:37 +0000121def set_loader(fxn):
122 """Set __loader__ on the returned module."""
123 def wrapper(self, *args, **kwargs):
124 module = fxn(self, *args, **kwargs)
125 if not hasattr(module, '__loader__'):
126 module.__loader__ = self
127 return module
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000128 _wrap(wrapper, fxn)
Brett Cannon2cf03a82009-03-10 05:17:37 +0000129 return wrapper
130
131
Brett Cannonce43ddf2009-03-12 22:28:55 +0000132def module_for_loader(fxn):
133 """Decorator to handle selecting the proper module for loaders.
134
Brett Cannon0e0d8a62009-03-15 00:00:19 +0000135 The decorated function is passed the module to use instead of the module
136 name. The module passed in to the function is either from sys.modules if
137 it already exists or is a new module which has __name__ set and is inserted
138 into sys.modules. If an exception is raised and the decorator created the
139 module it is subsequently removed from sys.modules.
Brett Cannonce43ddf2009-03-12 22:28:55 +0000140
Brett Cannon0e0d8a62009-03-15 00:00:19 +0000141 The decorator assumes that the decorated function takes the module name as
142 the second argument.
Brett Cannonce43ddf2009-03-12 22:28:55 +0000143
144 """
Brett Cannon61b14252010-07-03 21:48:25 +0000145 def decorated(self, fullname, *args, **kwargs):
Brett Cannonce43ddf2009-03-12 22:28:55 +0000146 module = sys.modules.get(fullname)
147 is_reload = bool(module)
148 if not is_reload:
149 # This must be done before open() is called as the 'io' module
150 # implicitly imports 'locale' and would otherwise trigger an
151 # infinite loop.
152 module = imp.new_module(fullname)
153 sys.modules[fullname] = module
154 try:
Brett Cannon61b14252010-07-03 21:48:25 +0000155 return fxn(self, module, *args, **kwargs)
Brett Cannonce43ddf2009-03-12 22:28:55 +0000156 except:
157 if not is_reload:
158 del sys.modules[fullname]
159 raise
160 _wrap(decorated, fxn)
161 return decorated
162
163
164def _check_name(method):
165 """Decorator to verify that the module being requested matches the one the
166 loader can handle.
167
168 The first argument (self) must define _name which the second argument is
169 comapred against. If the comparison fails then ImportError is raised.
170
171 """
172 def inner(self, name, *args, **kwargs):
173 if self._name != name:
174 raise ImportError("loader cannot handle %s" % name)
175 return method(self, name, *args, **kwargs)
176 _wrap(inner, method)
177 return inner
178
179
Brett Cannona113ac52009-03-15 01:41:33 +0000180def _requires_builtin(fxn):
181 """Decorator to verify the named module is built-in."""
182 def wrapper(self, fullname):
183 if fullname not in sys.builtin_module_names:
184 raise ImportError("{0} is not a built-in module".format(fullname))
185 return fxn(self, fullname)
186 _wrap(wrapper, fxn)
187 return wrapper
188
189
Brett Cannon8d110132009-03-15 02:20:16 +0000190def _requires_frozen(fxn):
191 """Decorator to verify the named module is frozen."""
192 def wrapper(self, fullname):
193 if not imp.is_frozen(fullname):
194 raise ImportError("{0} is not a frozen module".format(fullname))
195 return fxn(self, fullname)
196 _wrap(wrapper, fxn)
197 return wrapper
198
199
Brett Cannone9103d22009-03-12 22:37:06 +0000200def _suffix_list(suffix_type):
201 """Return a list of file suffixes based on the imp file type."""
202 return [suffix[0] for suffix in imp.get_suffixes()
203 if suffix[2] == suffix_type]
204
205
206# Loaders #####################################################################
Brett Cannonce43ddf2009-03-12 22:28:55 +0000207
Brett Cannon5abdc932009-01-22 22:43:07 +0000208class BuiltinImporter:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000209
Brett Cannon7aa21f72009-03-15 00:53:05 +0000210 """Meta path import for built-in modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000211
Brett Cannon7aa21f72009-03-15 00:53:05 +0000212 All methods are either class or static methods to avoid the need to
213 instantiate the class.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000214
215 """
216
Brett Cannon5abdc932009-01-22 22:43:07 +0000217 @classmethod
218 def find_module(cls, fullname, path=None):
Brett Cannon7aa21f72009-03-15 00:53:05 +0000219 """Find the built-in module.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000220
221 If 'path' is ever specified then the search is considered a failure.
222
223 """
224 if path is not None:
225 return None
Brett Cannon5abdc932009-01-22 22:43:07 +0000226 return cls if imp.is_builtin(fullname) else None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000227
Brett Cannon78246b62009-01-25 04:56:30 +0000228 @classmethod
Brett Cannon435aad82009-03-04 16:07:00 +0000229 @set_package
Brett Cannon2cf03a82009-03-10 05:17:37 +0000230 @set_loader
Brett Cannona113ac52009-03-15 01:41:33 +0000231 @_requires_builtin
Brett Cannon78246b62009-01-25 04:56:30 +0000232 def load_module(cls, fullname):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000233 """Load a built-in module."""
Brett Cannond2e7b332009-02-17 02:45:03 +0000234 is_reload = fullname in sys.modules
235 try:
236 return imp.init_builtin(fullname)
237 except:
238 if not is_reload and fullname in sys.modules:
239 del sys.modules[fullname]
240 raise
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000241
Brett Cannona113ac52009-03-15 01:41:33 +0000242 @classmethod
243 @_requires_builtin
244 def get_code(cls, fullname):
245 """Return None as built-in modules do not have code objects."""
246 return None
247
248 @classmethod
249 @_requires_builtin
250 def get_source(cls, fullname):
251 """Return None as built-in modules do not have source code."""
252 return None
253
254 @classmethod
255 @_requires_builtin
256 def is_package(cls, fullname):
257 """Return None as built-in module are never packages."""
258 return False
259
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000260
Brett Cannon5abdc932009-01-22 22:43:07 +0000261class FrozenImporter:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000262
Brett Cannon7aa21f72009-03-15 00:53:05 +0000263 """Meta path import for frozen modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000264
Brett Cannon7aa21f72009-03-15 00:53:05 +0000265 All methods are either class or static methods to avoid the need to
266 instantiate the class.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000267
Brett Cannon5abdc932009-01-22 22:43:07 +0000268 """
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000269
Brett Cannon5abdc932009-01-22 22:43:07 +0000270 @classmethod
271 def find_module(cls, fullname, path=None):
272 """Find a frozen module."""
273 return cls if imp.is_frozen(fullname) else None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000274
Brett Cannon5abdc932009-01-22 22:43:07 +0000275 @classmethod
Brett Cannon435aad82009-03-04 16:07:00 +0000276 @set_package
Brett Cannon2cf03a82009-03-10 05:17:37 +0000277 @set_loader
Brett Cannon8d110132009-03-15 02:20:16 +0000278 @_requires_frozen
Brett Cannon5abdc932009-01-22 22:43:07 +0000279 def load_module(cls, fullname):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000280 """Load a frozen module."""
Brett Cannond2e7b332009-02-17 02:45:03 +0000281 is_reload = fullname in sys.modules
282 try:
283 return imp.init_frozen(fullname)
284 except:
285 if not is_reload and fullname in sys.modules:
286 del sys.modules[fullname]
287 raise
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000288
Brett Cannon8d110132009-03-15 02:20:16 +0000289 @classmethod
290 @_requires_frozen
291 def get_code(cls, fullname):
292 """Return the code object for the frozen module."""
293 return imp.get_frozen_object(fullname)
294
295 @classmethod
296 @_requires_frozen
297 def get_source(cls, fullname):
298 """Return None as frozen modules do not have source code."""
299 return None
300
301 @classmethod
302 @_requires_frozen
303 def is_package(cls, fullname):
304 """Return if the frozen module is a package."""
305 return imp.is_frozen_package(fullname)
306
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000307
Brett Cannon61b14252010-07-03 21:48:25 +0000308class _LoaderBasics:
309
310 """Base class of common code needed by both SourceLoader and
311 _SourcelessFileLoader."""
312
313 def is_package(self, fullname):
314 """Concrete implementation of InspectLoader.is_package by checking if
315 the path returned by get_filename has a filename of '__init__.py'."""
316 filename = self.get_filename(fullname).rpartition(path_sep)[2]
317 return filename.rsplit('.', 1)[0] == '__init__'
318
319 def _bytes_from_bytecode(self, fullname, data, source_mtime):
320 """Return the marshalled bytes from bytecode, verifying the magic
321 number and timestamp alon the way.
322
323 If source_mtime is None then skip the timestamp check.
324
325 """
326 magic = data[:4]
327 raw_timestamp = data[4:8]
328 if len(magic) != 4 or magic != imp.get_magic():
329 raise ImportError("bad magic number in {}".format(fullname))
330 elif len(raw_timestamp) != 4:
331 raise EOFError("bad timestamp in {}".format(fullname))
332 elif source_mtime is not None:
333 if marshal._r_long(raw_timestamp) != source_mtime:
334 raise ImportError("bytecode is stale for {}".format(fullname))
335 # Can't return the code object as errors from marshal loading need to
336 # propagate even when source is available.
337 return data[8:]
338
339 @module_for_loader
340 def _load_module(self, module, *, sourceless=False):
341 """Helper for load_module able to handle either source or sourceless
342 loading."""
343 name = module.__name__
344 code_object = self.get_code(name)
345 module.__file__ = self.get_filename(name)
346 if not sourceless:
347 module.__cached__ = imp.cache_from_source(module.__file__)
348 else:
349 module.__cached__ = module.__file__
350 module.__package__ = name
351 if self.is_package(name):
352 module.__path__ = [module.__file__.rsplit(path_sep, 1)[0]]
353 else:
354 module.__package__ = module.__package__.rpartition('.')[0]
355 module.__loader__ = self
356 exec(code_object, module.__dict__)
357 return module
358
359
360class SourceLoader(_LoaderBasics):
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000361
362 def path_mtime(self, path:str) -> int:
363 """Optional method that returns the modification time for the specified
364 path.
365
366 Implementing this method allows the loader to read bytecode files.
367
368 """
369 raise NotImplementedError
370
371 def set_data(self, path:str, data:bytes) -> None:
372 """Optional method which writes data to a file path.
373
374 Implementing this method allows for the writing of bytecode files.
375
376 """
377 raise NotImplementedError
378
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000379
380 def get_source(self, fullname):
381 """Concrete implementation of InspectLoader.get_source."""
382 import tokenize
383 path = self.get_filename(fullname)
384 try:
385 source_bytes = self.get_data(path)
386 except IOError:
387 raise ImportError("source not available through get_data()")
388 encoding = tokenize.detect_encoding(_io.BytesIO(source_bytes).readline)
Brett Cannon418182e2010-07-03 22:32:41 +0000389 newline_decoder = _io.IncrementalNewlineDecoder(None, True)
390 return newline_decoder.decode(source_bytes.decode(encoding[0]))
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000391
392 def get_code(self, fullname):
393 """Concrete implementation of InspectLoader.get_code.
394
395 Reading of bytecode requires path_mtime to be implemented. To write
396 bytecode, set_data must also be implemented.
397
398 """
399 source_path = self.get_filename(fullname)
400 bytecode_path = imp.cache_from_source(source_path)
401 source_mtime = None
402 if bytecode_path is not None:
403 try:
404 source_mtime = self.path_mtime(source_path)
405 except NotImplementedError:
406 pass
407 else:
408 try:
409 data = self.get_data(bytecode_path)
410 except IOError:
411 pass
412 else:
Brett Cannon61b14252010-07-03 21:48:25 +0000413 try:
414 bytes_data = self._bytes_from_bytecode(fullname, data,
415 source_mtime)
416 except (ImportError, EOFError):
417 pass
418 else:
419 found = marshal.loads(bytes_data)
420 if isinstance(found, code_type):
421 return found
422 else:
423 msg = "Non-code object in {}"
424 raise ImportError(msg.format(bytecode_path))
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000425 source_bytes = self.get_data(source_path)
426 code_object = compile(source_bytes, source_path, 'exec',
427 dont_inherit=True)
428 if (not sys.dont_write_bytecode and bytecode_path is not None and
429 source_mtime is not None):
430 # If e.g. Jython ever implements imp.cache_from_source to have
431 # their own cached file format, this block of code will most likely
432 # throw an exception.
433 data = bytearray(imp.get_magic())
434 data.extend(marshal._w_long(source_mtime))
435 data.extend(marshal.dumps(code_object))
436 try:
437 self.set_data(bytecode_path, data)
438 except NotImplementedError:
439 pass
440 return code_object
441
Brett Cannon61b14252010-07-03 21:48:25 +0000442 def load_module(self, fullname):
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000443 """Concrete implementation of Loader.load_module.
444
445 Requires ExecutionLoader.get_filename and ResourceLoader.get_data to be
446 implemented to load source code. Use of bytecode is dictated by whether
447 get_code uses/writes bytecode.
448
449 """
Brett Cannon61b14252010-07-03 21:48:25 +0000450 return self._load_module(fullname)
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000451
452
Brett Cannon61b14252010-07-03 21:48:25 +0000453class _FileLoader:
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000454
Brett Cannon61b14252010-07-03 21:48:25 +0000455 """Base file loader class which implements the loader protocol methods that
456 require file system usage."""
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000457
458 def __init__(self, fullname, path):
Brett Cannon61b14252010-07-03 21:48:25 +0000459 """Cache the module name and the path to the file found by the
460 finder."""
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000461 self._name = fullname
462 self._path = path
463
464 @_check_name
465 def get_filename(self, fullname):
466 """Return the path to the source file as found by the finder."""
467 return self._path
468
Brett Cannon61b14252010-07-03 21:48:25 +0000469 def get_data(self, path):
470 """Return the data from path as raw bytes."""
471 with _closing(_io.FileIO(path, 'r')) as file:
472 return file.read()
473
474
475class _SourceFileLoader(_FileLoader, SourceLoader):
476
477 """Concrete implementation of SourceLoader using the file system."""
478
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000479 def path_mtime(self, path):
480 """Return the modification time for the path."""
481 return int(_os.stat(path).st_mtime)
482
Brett Cannon61b14252010-07-03 21:48:25 +0000483 def set_data(self, path, data):
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000484 """Write bytes data to a file."""
485 try:
Brett Cannon61b14252010-07-03 21:48:25 +0000486 with _closing(_io.FileIO(path, 'wb')) as file:
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000487 file.write(data)
488 except IOError as exc:
Brett Cannon61b14252010-07-03 21:48:25 +0000489 if exc.errno == errno.ENOENT:
490 directory, _, filename = path.rpartition(path_sep)
491 sub_directories = []
492 while not _path_isdir(directory):
493 directory, _, sub_dir = directory.rpartition(path_sep)
494 sub_directories.append(sub_dir)
495 for part in reversed(sub_directories):
496 directory = _path_join(directory, part)
497 try:
498 _os.mkdir(directory)
499 except IOError as exc:
500 if exc.errno != errno.EACCES:
501 raise
502 else:
503 return
504 return self.set_data(path, data)
505 elif exc.errno != errno.EACCES:
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000506 raise
507
508
Brett Cannon61b14252010-07-03 21:48:25 +0000509class _SourcelessFileLoader(_FileLoader, _LoaderBasics):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000510
Brett Cannon61b14252010-07-03 21:48:25 +0000511 """Loader which handles sourceless file imports."""
Brett Cannon91cf8822009-02-21 05:41:15 +0000512
Brett Cannon61b14252010-07-03 21:48:25 +0000513 def load_module(self, fullname):
514 return self._load_module(fullname, sourceless=True)
Brett Cannon69194272009-07-20 04:23:48 +0000515
Brett Cannon91cf8822009-02-21 05:41:15 +0000516 def get_code(self, fullname):
Brett Cannon61b14252010-07-03 21:48:25 +0000517 path = self.get_filename(fullname)
518 data = self.get_data(path)
519 bytes_data = self._bytes_from_bytecode(fullname, data, None)
520 found = marshal.loads(bytes_data)
521 if isinstance(found, code_type):
522 return found
523 else:
524 raise ImportError("Non-code object in {}".format(path))
Brett Cannon91cf8822009-02-21 05:41:15 +0000525
Brett Cannond43b30b2009-03-10 03:29:23 +0000526 def get_source(self, fullname):
Brett Cannon61b14252010-07-03 21:48:25 +0000527 """Return None as there is no source code."""
528 return None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000529
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000530
Brett Cannone9103d22009-03-12 22:37:06 +0000531class _ExtensionFileLoader:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000532
Brett Cannone9103d22009-03-12 22:37:06 +0000533 """Loader for extension modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000534
Brett Cannone9103d22009-03-12 22:37:06 +0000535 The constructor is designed to work with FileFinder.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000536
537 """
538
Brett Cannon61b14252010-07-03 21:48:25 +0000539 def __init__(self, name, path):
Brett Cannone9103d22009-03-12 22:37:06 +0000540 """Initialize the loader.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000541
Brett Cannone9103d22009-03-12 22:37:06 +0000542 If is_pkg is True then an exception is raised as extension modules
543 cannot be the __init__ module for an extension module.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000544
545 """
Brett Cannone9103d22009-03-12 22:37:06 +0000546 self._name = name
547 self._path = path
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000548
Brett Cannone9103d22009-03-12 22:37:06 +0000549 @_check_name
550 @set_package
551 @set_loader
552 def load_module(self, fullname):
553 """Load an extension module."""
554 is_reload = fullname in sys.modules
555 try:
556 return imp.load_dynamic(fullname, self._path)
557 except:
558 if not is_reload and fullname in sys.modules:
559 del sys.modules[fullname]
560 raise
561
562 @_check_name
563 def is_package(self, fullname):
564 """Return False as an extension module can never be a package."""
565 return False
566
567 @_check_name
568 def get_code(self, fullname):
569 """Return None as an extension module cannot create a code object."""
570 return None
571
572 @_check_name
573 def get_source(self, fullname):
574 """Return None as extension modules have no source code."""
575 return None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000576
577
Brett Cannone9103d22009-03-12 22:37:06 +0000578# Finders #####################################################################
Brett Cannon4afab6b2009-02-21 03:31:35 +0000579
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000580class PathFinder:
Brett Cannon1d376682009-02-02 19:19:36 +0000581
582 """Meta path finder for sys.(path|path_hooks|path_importer_cache)."""
583
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000584 @classmethod
Brett Cannon32732e32009-02-15 05:48:13 +0000585 def _path_hooks(cls, path, hooks=None):
586 """Search sequence of hooks for a finder for 'path'.
Brett Cannon1d376682009-02-02 19:19:36 +0000587
Brett Cannon32732e32009-02-15 05:48:13 +0000588 If 'hooks' is false then use sys.path_hooks.
Brett Cannon1d376682009-02-02 19:19:36 +0000589
590 """
Brett Cannon32732e32009-02-15 05:48:13 +0000591 if not hooks:
592 hooks = sys.path_hooks
593 for hook in hooks:
Brett Cannon1d376682009-02-02 19:19:36 +0000594 try:
595 return hook(path)
596 except ImportError:
597 continue
598 else:
Brett Cannon32732e32009-02-15 05:48:13 +0000599 raise ImportError("no path hook found for {0}".format(path))
Brett Cannon1d376682009-02-02 19:19:36 +0000600
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000601 @classmethod
Brett Cannon32732e32009-02-15 05:48:13 +0000602 def _path_importer_cache(cls, path, default=None):
Brett Cannon1d376682009-02-02 19:19:36 +0000603 """Get the finder for the path from sys.path_importer_cache.
604
605 If the path is not in the cache, find the appropriate finder and cache
606 it. If None is cached, get the default finder and cache that
607 (if applicable).
608
609 Because of NullImporter, some finder should be returned. The only
610 explicit fail case is if None is cached but the path cannot be used for
611 the default hook, for which ImportError is raised.
612
613 """
614 try:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000615 finder = sys.path_importer_cache[path]
Brett Cannon1d376682009-02-02 19:19:36 +0000616 except KeyError:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000617 finder = cls._path_hooks(path)
Brett Cannon1d376682009-02-02 19:19:36 +0000618 sys.path_importer_cache[path] = finder
619 else:
Brett Cannon32732e32009-02-15 05:48:13 +0000620 if finder is None and default:
Brett Cannon1d376682009-02-02 19:19:36 +0000621 # Raises ImportError on failure.
Brett Cannon32732e32009-02-15 05:48:13 +0000622 finder = default(path)
Brett Cannon1d376682009-02-02 19:19:36 +0000623 sys.path_importer_cache[path] = finder
624 return finder
625
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000626 @classmethod
627 def find_module(cls, fullname, path=None):
Brett Cannon7aa21f72009-03-15 00:53:05 +0000628 """Find the module on sys.path or 'path' based on sys.path_hooks and
629 sys.path_importer_cache."""
Brett Cannon1d376682009-02-02 19:19:36 +0000630 if not path:
631 path = sys.path
632 for entry in path:
633 try:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000634 finder = cls._path_importer_cache(entry)
Brett Cannon1d376682009-02-02 19:19:36 +0000635 except ImportError:
636 continue
Brett Cannon8593a752009-03-30 19:57:15 +0000637 if finder:
638 loader = finder.find_module(fullname)
639 if loader:
640 return loader
Brett Cannon1d376682009-02-02 19:19:36 +0000641 else:
642 return None
643
644
Brett Cannonf87e04d2009-03-12 22:47:53 +0000645class _FileFinder:
Brett Cannone9103d22009-03-12 22:37:06 +0000646
Brett Cannon61b14252010-07-03 21:48:25 +0000647 """File-based finder.
Brett Cannone9103d22009-03-12 22:37:06 +0000648
Brett Cannon61b14252010-07-03 21:48:25 +0000649 Constructor takes a list of objects detailing what file extensions their
650 loader supports along with whether it can be used for a package.
Brett Cannone9103d22009-03-12 22:37:06 +0000651
652 """
653
Brett Cannon61b14252010-07-03 21:48:25 +0000654 def __init__(self, path, *details):
655 """Initialize with finder details."""
656 packages = []
657 modules = []
658 for detail in details:
659 modules.extend((suffix, detail.loader) for suffix in detail.suffixes)
660 if detail.supports_packages:
661 packages.extend((suffix, detail.loader)
662 for suffix in detail.suffixes)
663 self.packages = packages
664 self.modules = modules
665 self.path = path
Brett Cannone9103d22009-03-12 22:37:06 +0000666
Brett Cannon61b14252010-07-03 21:48:25 +0000667 def find_module(self, fullname):
668 """Try to find a loader for the specified module."""
Brett Cannone9103d22009-03-12 22:37:06 +0000669 tail_module = fullname.rpartition('.')[2]
Brett Cannon61b14252010-07-03 21:48:25 +0000670 base_path = _path_join(self.path, tail_module)
671 if _path_isdir(base_path) and _case_ok(self.path, tail_module):
672 for suffix, loader in self.packages:
673 init_filename = '__init__' + suffix
674 full_path = _path_join(base_path, init_filename)
675 if (_path_isfile(full_path) and
676 _case_ok(base_path, init_filename)):
677 return loader(fullname, full_path)
678 else:
679 msg = "Not importing directory {}: missing __init__"
680 _warnings.warn(msg.format(base_path), ImportWarning)
681 for suffix, loader in self.modules:
682 mod_filename = tail_module + suffix
683 full_path = _path_join(self.path, mod_filename)
684 if _path_isfile(full_path) and _case_ok(self.path, mod_filename):
685 return loader(fullname, full_path)
686 return None
687
688class _SourceFinderDetails:
689
690 loader = _SourceFileLoader
691 supports_packages = True
692
693 def __init__(self):
694 self.suffixes = _suffix_list(imp.PY_SOURCE)
695
696class _SourcelessFinderDetails:
697
698 loader = _SourcelessFileLoader
699 supports_packages = True
700
701 def __init__(self):
702 self.suffixes = _suffix_list(imp.PY_COMPILED)
Brett Cannone9103d22009-03-12 22:37:06 +0000703
704
Brett Cannon61b14252010-07-03 21:48:25 +0000705class _ExtensionFinderDetails:
Brett Cannone9103d22009-03-12 22:37:06 +0000706
Brett Cannon61b14252010-07-03 21:48:25 +0000707 loader = _ExtensionFileLoader
708 supports_packages = False
Brett Cannone9103d22009-03-12 22:37:06 +0000709
Brett Cannon61b14252010-07-03 21:48:25 +0000710 def __init__(self):
711 self.suffixes = _suffix_list(imp.C_EXTENSION)
Brett Cannone9103d22009-03-12 22:37:06 +0000712
713
Brett Cannonce43ddf2009-03-12 22:28:55 +0000714# Import itself ###############################################################
715
Brett Cannon61b14252010-07-03 21:48:25 +0000716def _file_path_hook(path):
717 """If the path is a directory, return a file-based finder."""
718 if _path_isdir(path):
719 return _FileFinder(path, _ExtensionFinderDetails(),
720 _SourceFinderDetails(),
721 _SourcelessFinderDetails())
722 else:
723 raise ImportError("only directories are supported")
Brett Cannonce43ddf2009-03-12 22:28:55 +0000724
725
Brett Cannon61b14252010-07-03 21:48:25 +0000726_DEFAULT_PATH_HOOK = _file_path_hook
Brett Cannon2dee5972009-02-21 03:15:37 +0000727
Brett Cannon32732e32009-02-15 05:48:13 +0000728class _DefaultPathFinder(PathFinder):
729
730 """Subclass of PathFinder that implements implicit semantics for
731 __import__."""
732
Brett Cannon32732e32009-02-15 05:48:13 +0000733 @classmethod
734 def _path_hooks(cls, path):
735 """Search sys.path_hooks as well as implicit path hooks."""
736 try:
737 return super()._path_hooks(path)
738 except ImportError:
Brett Cannon2dee5972009-02-21 03:15:37 +0000739 implicit_hooks = [_DEFAULT_PATH_HOOK, imp.NullImporter]
Brett Cannon32732e32009-02-15 05:48:13 +0000740 return super()._path_hooks(path, implicit_hooks)
741
742 @classmethod
743 def _path_importer_cache(cls, path):
744 """Use the default path hook when None is stored in
745 sys.path_importer_cache."""
Brett Cannon2dee5972009-02-21 03:15:37 +0000746 return super()._path_importer_cache(path, _DEFAULT_PATH_HOOK)
Brett Cannon32732e32009-02-15 05:48:13 +0000747
748
Brett Cannone9103d22009-03-12 22:37:06 +0000749class _ImportLockContext:
750
751 """Context manager for the import lock."""
752
753 def __enter__(self):
754 """Acquire the import lock."""
755 imp.acquire_lock()
756
757 def __exit__(self, exc_type, exc_value, exc_traceback):
758 """Release the import lock regardless of any raised exceptions."""
759 imp.release_lock()
760
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000761
Brett Cannon32732e32009-02-15 05:48:13 +0000762_IMPLICIT_META_PATH = [BuiltinImporter, FrozenImporter, _DefaultPathFinder]
763
Brett Cannon7f9876c2009-02-06 02:47:33 +0000764def _gcd_import(name, package=None, level=0):
765 """Import and return the module based on its name, the package the call is
766 being made from, and the level adjustment.
767
768 This function represents the greatest common denominator of functionality
Brett Cannon2c318a12009-02-07 01:15:27 +0000769 between import_module and __import__. This includes settting __package__ if
770 the loader did not.
771
Brett Cannon7f9876c2009-02-06 02:47:33 +0000772 """
Brett Cannon2c318a12009-02-07 01:15:27 +0000773 if package:
774 if not hasattr(package, 'rindex'):
775 raise ValueError("__package__ not set to a string")
776 elif package not in sys.modules:
777 msg = ("Parent module {0!r} not loaded, cannot perform relative "
778 "import")
779 raise SystemError(msg.format(package))
780 if not name and level == 0:
781 raise ValueError("Empty module name")
Brett Cannon7f9876c2009-02-06 02:47:33 +0000782 if level > 0:
Brett Cannon2c318a12009-02-07 01:15:27 +0000783 dot = len(package)
Brett Cannon7f9876c2009-02-06 02:47:33 +0000784 for x in range(level, 1, -1):
785 try:
786 dot = package.rindex('.', 0, dot)
Brett Cannon7f9876c2009-02-06 02:47:33 +0000787 except ValueError:
Brett Cannon2c318a12009-02-07 01:15:27 +0000788 raise ValueError("attempted relative import beyond "
789 "top-level package")
790 if name:
791 name = "{0}.{1}".format(package[:dot], name)
792 else:
793 name = package[:dot]
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000794 with _ImportLockContext():
Brett Cannon7f9876c2009-02-06 02:47:33 +0000795 try:
Brett Cannon4d75fc12009-08-30 03:47:36 +0000796 module = sys.modules[name]
797 if module is None:
798 message = ("import of {} halted; "
799 "None in sys.modules".format(name))
800 raise ImportError(message)
801 return module
Brett Cannon7f9876c2009-02-06 02:47:33 +0000802 except KeyError:
803 pass
804 parent = name.rpartition('.')[0]
805 path = None
806 if parent:
807 if parent not in sys.modules:
Brett Cannon2c318a12009-02-07 01:15:27 +0000808 _gcd_import(parent)
809 # Backwards-compatibility; be nicer to skip the dict lookup.
810 parent_module = sys.modules[parent]
Brett Cannon1c1dcbf2009-08-30 20:22:21 +0000811 try:
812 path = parent_module.__path__
813 except AttributeError:
814 raise ImportError("no module named {}; "
815 "{} is not a package".format(name, parent))
Brett Cannon32732e32009-02-15 05:48:13 +0000816 meta_path = sys.meta_path + _IMPLICIT_META_PATH
Brett Cannon2c318a12009-02-07 01:15:27 +0000817 for finder in meta_path:
Brett Cannon7f9876c2009-02-06 02:47:33 +0000818 loader = finder.find_module(name, path)
Brett Cannon2c318a12009-02-07 01:15:27 +0000819 if loader is not None:
820 loader.load_module(name)
821 break
Brett Cannon7f9876c2009-02-06 02:47:33 +0000822 else:
823 raise ImportError("No module named {0}".format(name))
Brett Cannon2c318a12009-02-07 01:15:27 +0000824 # Backwards-compatibility; be nicer to skip the dict lookup.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000825 module = sys.modules[name]
826 if parent:
Brett Cannon2c318a12009-02-07 01:15:27 +0000827 # Set the module as an attribute on its parent.
828 setattr(parent_module, name.rpartition('.')[2], module)
829 # Set __package__ if the loader did not.
830 if not hasattr(module, '__package__') or module.__package__ is None:
831 # Watch out for what comes out of sys.modules to not be a module,
832 # e.g. an int.
833 try:
834 module.__package__ = module.__name__
835 if not hasattr(module, '__path__'):
836 module.__package__ = module.__package__.rpartition('.')[0]
837 except AttributeError:
838 pass
839 return module
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000840
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000841
Brett Cannon7aa21f72009-03-15 00:53:05 +0000842def __import__(name, globals={}, locals={}, fromlist=[], level=0):
Brett Cannon2c318a12009-02-07 01:15:27 +0000843 """Import a module.
844
845 The 'globals' argument is used to infer where the import is occuring from
846 to handle relative imports. The 'locals' argument is ignored. The
847 'fromlist' argument specifies what should exist as attributes on the module
848 being imported (e.g. ``from module import <fromlist>``). The 'level'
849 argument represents the package location to import from in a relative
850 import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
851
852 """
Brett Cannon6afbaef2009-08-30 19:08:58 +0000853 if not hasattr(name, 'rpartition'):
854 raise TypeError("module name must be str, not {}".format(type(name)))
Brett Cannon2c318a12009-02-07 01:15:27 +0000855 if level == 0:
856 module = _gcd_import(name)
857 else:
Brett Cannonde4ebfe2009-08-30 19:53:48 +0000858 # __package__ is not guaranteed to be defined or could be set to None
859 # to represent that it's proper value is unknown
860 package = globals.get('__package__')
861 if package is None:
Brett Cannon2c318a12009-02-07 01:15:27 +0000862 package = globals['__name__']
863 if '__path__' not in globals:
864 package = package.rpartition('.')[0]
865 module = _gcd_import(name, package, level)
866 # The hell that is fromlist ...
867 if not fromlist:
868 # Return up to the first dot in 'name'. This is complicated by the fact
869 # that 'name' may be relative.
870 if level == 0:
871 return sys.modules[name.partition('.')[0]]
872 elif not name:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000873 return module
Brett Cannon2c318a12009-02-07 01:15:27 +0000874 else:
875 cut_off = len(name) - len(name.partition('.')[0])
876 return sys.modules[module.__name__[:-cut_off]]
877 else:
878 # If a package was imported, try to import stuff from fromlist.
879 if hasattr(module, '__path__'):
880 if '*' in fromlist and hasattr(module, '__all__'):
Brett Cannon9e0e1a62009-08-30 18:28:46 +0000881 fromlist = list(fromlist)
Brett Cannon2c318a12009-02-07 01:15:27 +0000882 fromlist.remove('*')
883 fromlist.extend(module.__all__)
884 for x in (y for y in fromlist if not hasattr(module,y)):
885 try:
886 _gcd_import('{0}.{1}'.format(module.__name__, x))
887 except ImportError:
888 pass
889 return module