blob: 9130a928e8fc75409f6e2078d65d545962653fff [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."""
Brett Cannonee6d6472010-08-22 22:19:11 +0000485 parent, _, filename = path.rpartition(path_sep)
486 path_parts = []
487 # Figure out what directories are missing.
488 while parent and not _path_isdir(parent):
489 parent, _, part = parent.rpartition(path_sep)
490 path_parts.append(part)
491 # Create needed directories.
492 for part in reversed(path_parts):
493 parent = _path_join(parent, part)
494 try:
495 _os.mkdir(parent)
Brett Cannona7ceeb32010-08-26 21:07:13 +0000496 except OSError as exc:
Brett Cannonee6d6472010-08-22 22:19:11 +0000497 # Probably another Python process already created the dir.
498 if exc.errno == errno.EEXIST:
499 continue
Brett Cannona7ceeb32010-08-26 21:07:13 +0000500 else:
501 raise
502 except IOError as exc:
Brett Cannonee6d6472010-08-22 22:19:11 +0000503 # If can't get proper access, then just forget about writing
504 # the data.
Brett Cannona7ceeb32010-08-26 21:07:13 +0000505 if exc.errno == errno.EACCES:
Brett Cannonee6d6472010-08-22 22:19:11 +0000506 return
507 else:
508 raise
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000509 try:
Brett Cannonee6d6472010-08-22 22:19:11 +0000510 with _io.FileIO(path, 'wb') as file:
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000511 file.write(data)
512 except IOError as exc:
Brett Cannonee6d6472010-08-22 22:19:11 +0000513 # Don't worry if you can't write bytecode.
514 if exc.errno == errno.EACCES:
515 return
516 else:
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000517 raise
518
519
Brett Cannon61b14252010-07-03 21:48:25 +0000520class _SourcelessFileLoader(_FileLoader, _LoaderBasics):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000521
Brett Cannon61b14252010-07-03 21:48:25 +0000522 """Loader which handles sourceless file imports."""
Brett Cannon91cf8822009-02-21 05:41:15 +0000523
Brett Cannon61b14252010-07-03 21:48:25 +0000524 def load_module(self, fullname):
525 return self._load_module(fullname, sourceless=True)
Brett Cannon69194272009-07-20 04:23:48 +0000526
Brett Cannon91cf8822009-02-21 05:41:15 +0000527 def get_code(self, fullname):
Brett Cannon61b14252010-07-03 21:48:25 +0000528 path = self.get_filename(fullname)
529 data = self.get_data(path)
530 bytes_data = self._bytes_from_bytecode(fullname, data, None)
531 found = marshal.loads(bytes_data)
532 if isinstance(found, code_type):
533 return found
534 else:
535 raise ImportError("Non-code object in {}".format(path))
Brett Cannon91cf8822009-02-21 05:41:15 +0000536
Brett Cannond43b30b2009-03-10 03:29:23 +0000537 def get_source(self, fullname):
Brett Cannon61b14252010-07-03 21:48:25 +0000538 """Return None as there is no source code."""
539 return None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000540
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000541
Brett Cannone9103d22009-03-12 22:37:06 +0000542class _ExtensionFileLoader:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000543
Brett Cannone9103d22009-03-12 22:37:06 +0000544 """Loader for extension modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000545
Brett Cannone9103d22009-03-12 22:37:06 +0000546 The constructor is designed to work with FileFinder.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000547
548 """
549
Brett Cannon61b14252010-07-03 21:48:25 +0000550 def __init__(self, name, path):
Brett Cannone9103d22009-03-12 22:37:06 +0000551 """Initialize the loader.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000552
Brett Cannone9103d22009-03-12 22:37:06 +0000553 If is_pkg is True then an exception is raised as extension modules
554 cannot be the __init__ module for an extension module.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000555
556 """
Brett Cannone9103d22009-03-12 22:37:06 +0000557 self._name = name
558 self._path = path
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000559
Brett Cannone9103d22009-03-12 22:37:06 +0000560 @_check_name
561 @set_package
562 @set_loader
563 def load_module(self, fullname):
564 """Load an extension module."""
565 is_reload = fullname in sys.modules
566 try:
567 return imp.load_dynamic(fullname, self._path)
568 except:
569 if not is_reload and fullname in sys.modules:
570 del sys.modules[fullname]
571 raise
572
573 @_check_name
574 def is_package(self, fullname):
575 """Return False as an extension module can never be a package."""
576 return False
577
578 @_check_name
579 def get_code(self, fullname):
580 """Return None as an extension module cannot create a code object."""
581 return None
582
583 @_check_name
584 def get_source(self, fullname):
585 """Return None as extension modules have no source code."""
586 return None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000587
588
Brett Cannone9103d22009-03-12 22:37:06 +0000589# Finders #####################################################################
Brett Cannon4afab6b2009-02-21 03:31:35 +0000590
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000591class PathFinder:
Brett Cannon1d376682009-02-02 19:19:36 +0000592
593 """Meta path finder for sys.(path|path_hooks|path_importer_cache)."""
594
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000595 @classmethod
Brett Cannon32732e32009-02-15 05:48:13 +0000596 def _path_hooks(cls, path, hooks=None):
597 """Search sequence of hooks for a finder for 'path'.
Brett Cannon1d376682009-02-02 19:19:36 +0000598
Brett Cannon32732e32009-02-15 05:48:13 +0000599 If 'hooks' is false then use sys.path_hooks.
Brett Cannon1d376682009-02-02 19:19:36 +0000600
601 """
Brett Cannon32732e32009-02-15 05:48:13 +0000602 if not hooks:
603 hooks = sys.path_hooks
604 for hook in hooks:
Brett Cannon1d376682009-02-02 19:19:36 +0000605 try:
606 return hook(path)
607 except ImportError:
608 continue
609 else:
Brett Cannon32732e32009-02-15 05:48:13 +0000610 raise ImportError("no path hook found for {0}".format(path))
Brett Cannon1d376682009-02-02 19:19:36 +0000611
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000612 @classmethod
Brett Cannon32732e32009-02-15 05:48:13 +0000613 def _path_importer_cache(cls, path, default=None):
Brett Cannon1d376682009-02-02 19:19:36 +0000614 """Get the finder for the path from sys.path_importer_cache.
615
616 If the path is not in the cache, find the appropriate finder and cache
617 it. If None is cached, get the default finder and cache that
618 (if applicable).
619
620 Because of NullImporter, some finder should be returned. The only
621 explicit fail case is if None is cached but the path cannot be used for
622 the default hook, for which ImportError is raised.
623
624 """
625 try:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000626 finder = sys.path_importer_cache[path]
Brett Cannon1d376682009-02-02 19:19:36 +0000627 except KeyError:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000628 finder = cls._path_hooks(path)
Brett Cannon1d376682009-02-02 19:19:36 +0000629 sys.path_importer_cache[path] = finder
630 else:
Brett Cannon32732e32009-02-15 05:48:13 +0000631 if finder is None and default:
Brett Cannon1d376682009-02-02 19:19:36 +0000632 # Raises ImportError on failure.
Brett Cannon32732e32009-02-15 05:48:13 +0000633 finder = default(path)
Brett Cannon1d376682009-02-02 19:19:36 +0000634 sys.path_importer_cache[path] = finder
635 return finder
636
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000637 @classmethod
638 def find_module(cls, fullname, path=None):
Brett Cannon7aa21f72009-03-15 00:53:05 +0000639 """Find the module on sys.path or 'path' based on sys.path_hooks and
640 sys.path_importer_cache."""
Brett Cannon1d376682009-02-02 19:19:36 +0000641 if not path:
642 path = sys.path
643 for entry in path:
644 try:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000645 finder = cls._path_importer_cache(entry)
Brett Cannon1d376682009-02-02 19:19:36 +0000646 except ImportError:
647 continue
Brett Cannon8593a752009-03-30 19:57:15 +0000648 if finder:
649 loader = finder.find_module(fullname)
650 if loader:
651 return loader
Brett Cannon1d376682009-02-02 19:19:36 +0000652 else:
653 return None
654
655
Brett Cannonf87e04d2009-03-12 22:47:53 +0000656class _FileFinder:
Brett Cannone9103d22009-03-12 22:37:06 +0000657
Brett Cannon61b14252010-07-03 21:48:25 +0000658 """File-based finder.
Brett Cannone9103d22009-03-12 22:37:06 +0000659
Brett Cannon61b14252010-07-03 21:48:25 +0000660 Constructor takes a list of objects detailing what file extensions their
661 loader supports along with whether it can be used for a package.
Brett Cannone9103d22009-03-12 22:37:06 +0000662
663 """
664
Brett Cannon61b14252010-07-03 21:48:25 +0000665 def __init__(self, path, *details):
666 """Initialize with finder details."""
667 packages = []
668 modules = []
669 for detail in details:
670 modules.extend((suffix, detail.loader) for suffix in detail.suffixes)
671 if detail.supports_packages:
672 packages.extend((suffix, detail.loader)
673 for suffix in detail.suffixes)
674 self.packages = packages
675 self.modules = modules
676 self.path = path
Brett Cannone9103d22009-03-12 22:37:06 +0000677
Brett Cannon61b14252010-07-03 21:48:25 +0000678 def find_module(self, fullname):
679 """Try to find a loader for the specified module."""
Brett Cannone9103d22009-03-12 22:37:06 +0000680 tail_module = fullname.rpartition('.')[2]
Brett Cannon61b14252010-07-03 21:48:25 +0000681 base_path = _path_join(self.path, tail_module)
682 if _path_isdir(base_path) and _case_ok(self.path, tail_module):
683 for suffix, loader in self.packages:
684 init_filename = '__init__' + suffix
685 full_path = _path_join(base_path, init_filename)
686 if (_path_isfile(full_path) and
687 _case_ok(base_path, init_filename)):
688 return loader(fullname, full_path)
689 else:
690 msg = "Not importing directory {}: missing __init__"
691 _warnings.warn(msg.format(base_path), ImportWarning)
692 for suffix, loader in self.modules:
693 mod_filename = tail_module + suffix
694 full_path = _path_join(self.path, mod_filename)
695 if _path_isfile(full_path) and _case_ok(self.path, mod_filename):
696 return loader(fullname, full_path)
697 return None
698
699class _SourceFinderDetails:
700
701 loader = _SourceFileLoader
702 supports_packages = True
703
704 def __init__(self):
705 self.suffixes = _suffix_list(imp.PY_SOURCE)
706
707class _SourcelessFinderDetails:
708
709 loader = _SourcelessFileLoader
710 supports_packages = True
711
712 def __init__(self):
713 self.suffixes = _suffix_list(imp.PY_COMPILED)
Brett Cannone9103d22009-03-12 22:37:06 +0000714
715
Brett Cannon61b14252010-07-03 21:48:25 +0000716class _ExtensionFinderDetails:
Brett Cannone9103d22009-03-12 22:37:06 +0000717
Brett Cannon61b14252010-07-03 21:48:25 +0000718 loader = _ExtensionFileLoader
719 supports_packages = False
Brett Cannone9103d22009-03-12 22:37:06 +0000720
Brett Cannon61b14252010-07-03 21:48:25 +0000721 def __init__(self):
722 self.suffixes = _suffix_list(imp.C_EXTENSION)
Brett Cannone9103d22009-03-12 22:37:06 +0000723
724
Brett Cannonce43ddf2009-03-12 22:28:55 +0000725# Import itself ###############################################################
726
Brett Cannon61b14252010-07-03 21:48:25 +0000727def _file_path_hook(path):
728 """If the path is a directory, return a file-based finder."""
729 if _path_isdir(path):
730 return _FileFinder(path, _ExtensionFinderDetails(),
731 _SourceFinderDetails(),
732 _SourcelessFinderDetails())
733 else:
734 raise ImportError("only directories are supported")
Brett Cannonce43ddf2009-03-12 22:28:55 +0000735
736
Brett Cannon61b14252010-07-03 21:48:25 +0000737_DEFAULT_PATH_HOOK = _file_path_hook
Brett Cannon2dee5972009-02-21 03:15:37 +0000738
Brett Cannon32732e32009-02-15 05:48:13 +0000739class _DefaultPathFinder(PathFinder):
740
741 """Subclass of PathFinder that implements implicit semantics for
742 __import__."""
743
Brett Cannon32732e32009-02-15 05:48:13 +0000744 @classmethod
745 def _path_hooks(cls, path):
746 """Search sys.path_hooks as well as implicit path hooks."""
747 try:
748 return super()._path_hooks(path)
749 except ImportError:
Brett Cannon2dee5972009-02-21 03:15:37 +0000750 implicit_hooks = [_DEFAULT_PATH_HOOK, imp.NullImporter]
Brett Cannon32732e32009-02-15 05:48:13 +0000751 return super()._path_hooks(path, implicit_hooks)
752
753 @classmethod
754 def _path_importer_cache(cls, path):
755 """Use the default path hook when None is stored in
756 sys.path_importer_cache."""
Brett Cannon2dee5972009-02-21 03:15:37 +0000757 return super()._path_importer_cache(path, _DEFAULT_PATH_HOOK)
Brett Cannon32732e32009-02-15 05:48:13 +0000758
759
Brett Cannone9103d22009-03-12 22:37:06 +0000760class _ImportLockContext:
761
762 """Context manager for the import lock."""
763
764 def __enter__(self):
765 """Acquire the import lock."""
766 imp.acquire_lock()
767
768 def __exit__(self, exc_type, exc_value, exc_traceback):
769 """Release the import lock regardless of any raised exceptions."""
770 imp.release_lock()
771
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000772
Brett Cannon32732e32009-02-15 05:48:13 +0000773_IMPLICIT_META_PATH = [BuiltinImporter, FrozenImporter, _DefaultPathFinder]
774
Brett Cannon7f9876c2009-02-06 02:47:33 +0000775def _gcd_import(name, package=None, level=0):
776 """Import and return the module based on its name, the package the call is
777 being made from, and the level adjustment.
778
779 This function represents the greatest common denominator of functionality
Brett Cannon2c318a12009-02-07 01:15:27 +0000780 between import_module and __import__. This includes settting __package__ if
781 the loader did not.
782
Brett Cannon7f9876c2009-02-06 02:47:33 +0000783 """
Brett Cannon2c318a12009-02-07 01:15:27 +0000784 if package:
785 if not hasattr(package, 'rindex'):
786 raise ValueError("__package__ not set to a string")
787 elif package not in sys.modules:
788 msg = ("Parent module {0!r} not loaded, cannot perform relative "
789 "import")
790 raise SystemError(msg.format(package))
791 if not name and level == 0:
792 raise ValueError("Empty module name")
Brett Cannon7f9876c2009-02-06 02:47:33 +0000793 if level > 0:
Brett Cannon2c318a12009-02-07 01:15:27 +0000794 dot = len(package)
Brett Cannon7f9876c2009-02-06 02:47:33 +0000795 for x in range(level, 1, -1):
796 try:
797 dot = package.rindex('.', 0, dot)
Brett Cannon7f9876c2009-02-06 02:47:33 +0000798 except ValueError:
Brett Cannon2c318a12009-02-07 01:15:27 +0000799 raise ValueError("attempted relative import beyond "
800 "top-level package")
801 if name:
802 name = "{0}.{1}".format(package[:dot], name)
803 else:
804 name = package[:dot]
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000805 with _ImportLockContext():
Brett Cannon7f9876c2009-02-06 02:47:33 +0000806 try:
Brett Cannon4d75fc12009-08-30 03:47:36 +0000807 module = sys.modules[name]
808 if module is None:
809 message = ("import of {} halted; "
810 "None in sys.modules".format(name))
811 raise ImportError(message)
812 return module
Brett Cannon7f9876c2009-02-06 02:47:33 +0000813 except KeyError:
814 pass
815 parent = name.rpartition('.')[0]
816 path = None
817 if parent:
818 if parent not in sys.modules:
Brett Cannon2c318a12009-02-07 01:15:27 +0000819 _gcd_import(parent)
820 # Backwards-compatibility; be nicer to skip the dict lookup.
821 parent_module = sys.modules[parent]
Brett Cannon1c1dcbf2009-08-30 20:22:21 +0000822 try:
823 path = parent_module.__path__
824 except AttributeError:
825 raise ImportError("no module named {}; "
826 "{} is not a package".format(name, parent))
Brett Cannon32732e32009-02-15 05:48:13 +0000827 meta_path = sys.meta_path + _IMPLICIT_META_PATH
Brett Cannon2c318a12009-02-07 01:15:27 +0000828 for finder in meta_path:
Brett Cannon7f9876c2009-02-06 02:47:33 +0000829 loader = finder.find_module(name, path)
Brett Cannon2c318a12009-02-07 01:15:27 +0000830 if loader is not None:
831 loader.load_module(name)
832 break
Brett Cannon7f9876c2009-02-06 02:47:33 +0000833 else:
834 raise ImportError("No module named {0}".format(name))
Brett Cannon2c318a12009-02-07 01:15:27 +0000835 # Backwards-compatibility; be nicer to skip the dict lookup.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000836 module = sys.modules[name]
837 if parent:
Brett Cannon2c318a12009-02-07 01:15:27 +0000838 # Set the module as an attribute on its parent.
839 setattr(parent_module, name.rpartition('.')[2], module)
840 # Set __package__ if the loader did not.
841 if not hasattr(module, '__package__') or module.__package__ is None:
842 # Watch out for what comes out of sys.modules to not be a module,
843 # e.g. an int.
844 try:
845 module.__package__ = module.__name__
846 if not hasattr(module, '__path__'):
847 module.__package__ = module.__package__.rpartition('.')[0]
848 except AttributeError:
849 pass
850 return module
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000851
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000852
Brett Cannon7aa21f72009-03-15 00:53:05 +0000853def __import__(name, globals={}, locals={}, fromlist=[], level=0):
Brett Cannon2c318a12009-02-07 01:15:27 +0000854 """Import a module.
855
856 The 'globals' argument is used to infer where the import is occuring from
857 to handle relative imports. The 'locals' argument is ignored. The
858 'fromlist' argument specifies what should exist as attributes on the module
859 being imported (e.g. ``from module import <fromlist>``). The 'level'
860 argument represents the package location to import from in a relative
861 import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
862
863 """
Brett Cannon6afbaef2009-08-30 19:08:58 +0000864 if not hasattr(name, 'rpartition'):
865 raise TypeError("module name must be str, not {}".format(type(name)))
Brett Cannon2c318a12009-02-07 01:15:27 +0000866 if level == 0:
867 module = _gcd_import(name)
868 else:
Brett Cannonde4ebfe2009-08-30 19:53:48 +0000869 # __package__ is not guaranteed to be defined or could be set to None
870 # to represent that it's proper value is unknown
871 package = globals.get('__package__')
872 if package is None:
Brett Cannon2c318a12009-02-07 01:15:27 +0000873 package = globals['__name__']
874 if '__path__' not in globals:
875 package = package.rpartition('.')[0]
876 module = _gcd_import(name, package, level)
877 # The hell that is fromlist ...
878 if not fromlist:
879 # Return up to the first dot in 'name'. This is complicated by the fact
880 # that 'name' may be relative.
881 if level == 0:
882 return sys.modules[name.partition('.')[0]]
883 elif not name:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000884 return module
Brett Cannon2c318a12009-02-07 01:15:27 +0000885 else:
886 cut_off = len(name) - len(name.partition('.')[0])
887 return sys.modules[module.__name__[:-cut_off]]
888 else:
889 # If a package was imported, try to import stuff from fromlist.
890 if hasattr(module, '__path__'):
891 if '*' in fromlist and hasattr(module, '__all__'):
Brett Cannon9e0e1a62009-08-30 18:28:46 +0000892 fromlist = list(fromlist)
Brett Cannon2c318a12009-02-07 01:15:27 +0000893 fromlist.remove('*')
894 fromlist.extend(module.__all__)
895 for x in (y for y in fromlist if not hasattr(module,y)):
896 try:
897 _gcd_import('{0}.{1}'.format(module.__name__, x))
898 except ImportError:
899 pass
900 return module