blob: 35b42ca86e67880896a8d279a5c68659a50c318a [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)
496 except IOError as exc:
497 # Probably another Python process already created the dir.
498 if exc.errno == errno.EEXIST:
499 continue
500 # If can't get proper access, then just forget about writing
501 # the data.
502 elif errno == errno.EACCES:
503 return
504 else:
505 raise
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000506 try:
Brett Cannonee6d6472010-08-22 22:19:11 +0000507 with _io.FileIO(path, 'wb') as file:
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000508 file.write(data)
509 except IOError as exc:
Brett Cannonee6d6472010-08-22 22:19:11 +0000510 # Don't worry if you can't write bytecode.
511 if exc.errno == errno.EACCES:
512 return
513 else:
Brett Cannon0cf9e6a2010-06-28 04:57:24 +0000514 raise
515
516
Brett Cannon61b14252010-07-03 21:48:25 +0000517class _SourcelessFileLoader(_FileLoader, _LoaderBasics):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000518
Brett Cannon61b14252010-07-03 21:48:25 +0000519 """Loader which handles sourceless file imports."""
Brett Cannon91cf8822009-02-21 05:41:15 +0000520
Brett Cannon61b14252010-07-03 21:48:25 +0000521 def load_module(self, fullname):
522 return self._load_module(fullname, sourceless=True)
Brett Cannon69194272009-07-20 04:23:48 +0000523
Brett Cannon91cf8822009-02-21 05:41:15 +0000524 def get_code(self, fullname):
Brett Cannon61b14252010-07-03 21:48:25 +0000525 path = self.get_filename(fullname)
526 data = self.get_data(path)
527 bytes_data = self._bytes_from_bytecode(fullname, data, None)
528 found = marshal.loads(bytes_data)
529 if isinstance(found, code_type):
530 return found
531 else:
532 raise ImportError("Non-code object in {}".format(path))
Brett Cannon91cf8822009-02-21 05:41:15 +0000533
Brett Cannond43b30b2009-03-10 03:29:23 +0000534 def get_source(self, fullname):
Brett Cannon61b14252010-07-03 21:48:25 +0000535 """Return None as there is no source code."""
536 return None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000537
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000538
Brett Cannone9103d22009-03-12 22:37:06 +0000539class _ExtensionFileLoader:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000540
Brett Cannone9103d22009-03-12 22:37:06 +0000541 """Loader for extension modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000542
Brett Cannone9103d22009-03-12 22:37:06 +0000543 The constructor is designed to work with FileFinder.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000544
545 """
546
Brett Cannon61b14252010-07-03 21:48:25 +0000547 def __init__(self, name, path):
Brett Cannone9103d22009-03-12 22:37:06 +0000548 """Initialize the loader.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000549
Brett Cannone9103d22009-03-12 22:37:06 +0000550 If is_pkg is True then an exception is raised as extension modules
551 cannot be the __init__ module for an extension module.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000552
553 """
Brett Cannone9103d22009-03-12 22:37:06 +0000554 self._name = name
555 self._path = path
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000556
Brett Cannone9103d22009-03-12 22:37:06 +0000557 @_check_name
558 @set_package
559 @set_loader
560 def load_module(self, fullname):
561 """Load an extension module."""
562 is_reload = fullname in sys.modules
563 try:
564 return imp.load_dynamic(fullname, self._path)
565 except:
566 if not is_reload and fullname in sys.modules:
567 del sys.modules[fullname]
568 raise
569
570 @_check_name
571 def is_package(self, fullname):
572 """Return False as an extension module can never be a package."""
573 return False
574
575 @_check_name
576 def get_code(self, fullname):
577 """Return None as an extension module cannot create a code object."""
578 return None
579
580 @_check_name
581 def get_source(self, fullname):
582 """Return None as extension modules have no source code."""
583 return None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000584
585
Brett Cannone9103d22009-03-12 22:37:06 +0000586# Finders #####################################################################
Brett Cannon4afab6b2009-02-21 03:31:35 +0000587
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000588class PathFinder:
Brett Cannon1d376682009-02-02 19:19:36 +0000589
590 """Meta path finder for sys.(path|path_hooks|path_importer_cache)."""
591
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000592 @classmethod
Brett Cannon32732e32009-02-15 05:48:13 +0000593 def _path_hooks(cls, path, hooks=None):
594 """Search sequence of hooks for a finder for 'path'.
Brett Cannon1d376682009-02-02 19:19:36 +0000595
Brett Cannon32732e32009-02-15 05:48:13 +0000596 If 'hooks' is false then use sys.path_hooks.
Brett Cannon1d376682009-02-02 19:19:36 +0000597
598 """
Brett Cannon32732e32009-02-15 05:48:13 +0000599 if not hooks:
600 hooks = sys.path_hooks
601 for hook in hooks:
Brett Cannon1d376682009-02-02 19:19:36 +0000602 try:
603 return hook(path)
604 except ImportError:
605 continue
606 else:
Brett Cannon32732e32009-02-15 05:48:13 +0000607 raise ImportError("no path hook found for {0}".format(path))
Brett Cannon1d376682009-02-02 19:19:36 +0000608
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000609 @classmethod
Brett Cannon32732e32009-02-15 05:48:13 +0000610 def _path_importer_cache(cls, path, default=None):
Brett Cannon1d376682009-02-02 19:19:36 +0000611 """Get the finder for the path from sys.path_importer_cache.
612
613 If the path is not in the cache, find the appropriate finder and cache
614 it. If None is cached, get the default finder and cache that
615 (if applicable).
616
617 Because of NullImporter, some finder should be returned. The only
618 explicit fail case is if None is cached but the path cannot be used for
619 the default hook, for which ImportError is raised.
620
621 """
622 try:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000623 finder = sys.path_importer_cache[path]
Brett Cannon1d376682009-02-02 19:19:36 +0000624 except KeyError:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000625 finder = cls._path_hooks(path)
Brett Cannon1d376682009-02-02 19:19:36 +0000626 sys.path_importer_cache[path] = finder
627 else:
Brett Cannon32732e32009-02-15 05:48:13 +0000628 if finder is None and default:
Brett Cannon1d376682009-02-02 19:19:36 +0000629 # Raises ImportError on failure.
Brett Cannon32732e32009-02-15 05:48:13 +0000630 finder = default(path)
Brett Cannon1d376682009-02-02 19:19:36 +0000631 sys.path_importer_cache[path] = finder
632 return finder
633
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000634 @classmethod
635 def find_module(cls, fullname, path=None):
Brett Cannon7aa21f72009-03-15 00:53:05 +0000636 """Find the module on sys.path or 'path' based on sys.path_hooks and
637 sys.path_importer_cache."""
Brett Cannon1d376682009-02-02 19:19:36 +0000638 if not path:
639 path = sys.path
640 for entry in path:
641 try:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000642 finder = cls._path_importer_cache(entry)
Brett Cannon1d376682009-02-02 19:19:36 +0000643 except ImportError:
644 continue
Brett Cannon8593a752009-03-30 19:57:15 +0000645 if finder:
646 loader = finder.find_module(fullname)
647 if loader:
648 return loader
Brett Cannon1d376682009-02-02 19:19:36 +0000649 else:
650 return None
651
652
Brett Cannonf87e04d2009-03-12 22:47:53 +0000653class _FileFinder:
Brett Cannone9103d22009-03-12 22:37:06 +0000654
Brett Cannon61b14252010-07-03 21:48:25 +0000655 """File-based finder.
Brett Cannone9103d22009-03-12 22:37:06 +0000656
Brett Cannon61b14252010-07-03 21:48:25 +0000657 Constructor takes a list of objects detailing what file extensions their
658 loader supports along with whether it can be used for a package.
Brett Cannone9103d22009-03-12 22:37:06 +0000659
660 """
661
Brett Cannon61b14252010-07-03 21:48:25 +0000662 def __init__(self, path, *details):
663 """Initialize with finder details."""
664 packages = []
665 modules = []
666 for detail in details:
667 modules.extend((suffix, detail.loader) for suffix in detail.suffixes)
668 if detail.supports_packages:
669 packages.extend((suffix, detail.loader)
670 for suffix in detail.suffixes)
671 self.packages = packages
672 self.modules = modules
673 self.path = path
Brett Cannone9103d22009-03-12 22:37:06 +0000674
Brett Cannon61b14252010-07-03 21:48:25 +0000675 def find_module(self, fullname):
676 """Try to find a loader for the specified module."""
Brett Cannone9103d22009-03-12 22:37:06 +0000677 tail_module = fullname.rpartition('.')[2]
Brett Cannon61b14252010-07-03 21:48:25 +0000678 base_path = _path_join(self.path, tail_module)
679 if _path_isdir(base_path) and _case_ok(self.path, tail_module):
680 for suffix, loader in self.packages:
681 init_filename = '__init__' + suffix
682 full_path = _path_join(base_path, init_filename)
683 if (_path_isfile(full_path) and
684 _case_ok(base_path, init_filename)):
685 return loader(fullname, full_path)
686 else:
687 msg = "Not importing directory {}: missing __init__"
688 _warnings.warn(msg.format(base_path), ImportWarning)
689 for suffix, loader in self.modules:
690 mod_filename = tail_module + suffix
691 full_path = _path_join(self.path, mod_filename)
692 if _path_isfile(full_path) and _case_ok(self.path, mod_filename):
693 return loader(fullname, full_path)
694 return None
695
696class _SourceFinderDetails:
697
698 loader = _SourceFileLoader
699 supports_packages = True
700
701 def __init__(self):
702 self.suffixes = _suffix_list(imp.PY_SOURCE)
703
704class _SourcelessFinderDetails:
705
706 loader = _SourcelessFileLoader
707 supports_packages = True
708
709 def __init__(self):
710 self.suffixes = _suffix_list(imp.PY_COMPILED)
Brett Cannone9103d22009-03-12 22:37:06 +0000711
712
Brett Cannon61b14252010-07-03 21:48:25 +0000713class _ExtensionFinderDetails:
Brett Cannone9103d22009-03-12 22:37:06 +0000714
Brett Cannon61b14252010-07-03 21:48:25 +0000715 loader = _ExtensionFileLoader
716 supports_packages = False
Brett Cannone9103d22009-03-12 22:37:06 +0000717
Brett Cannon61b14252010-07-03 21:48:25 +0000718 def __init__(self):
719 self.suffixes = _suffix_list(imp.C_EXTENSION)
Brett Cannone9103d22009-03-12 22:37:06 +0000720
721
Brett Cannonce43ddf2009-03-12 22:28:55 +0000722# Import itself ###############################################################
723
Brett Cannon61b14252010-07-03 21:48:25 +0000724def _file_path_hook(path):
725 """If the path is a directory, return a file-based finder."""
726 if _path_isdir(path):
727 return _FileFinder(path, _ExtensionFinderDetails(),
728 _SourceFinderDetails(),
729 _SourcelessFinderDetails())
730 else:
731 raise ImportError("only directories are supported")
Brett Cannonce43ddf2009-03-12 22:28:55 +0000732
733
Brett Cannon61b14252010-07-03 21:48:25 +0000734_DEFAULT_PATH_HOOK = _file_path_hook
Brett Cannon2dee5972009-02-21 03:15:37 +0000735
Brett Cannon32732e32009-02-15 05:48:13 +0000736class _DefaultPathFinder(PathFinder):
737
738 """Subclass of PathFinder that implements implicit semantics for
739 __import__."""
740
Brett Cannon32732e32009-02-15 05:48:13 +0000741 @classmethod
742 def _path_hooks(cls, path):
743 """Search sys.path_hooks as well as implicit path hooks."""
744 try:
745 return super()._path_hooks(path)
746 except ImportError:
Brett Cannon2dee5972009-02-21 03:15:37 +0000747 implicit_hooks = [_DEFAULT_PATH_HOOK, imp.NullImporter]
Brett Cannon32732e32009-02-15 05:48:13 +0000748 return super()._path_hooks(path, implicit_hooks)
749
750 @classmethod
751 def _path_importer_cache(cls, path):
752 """Use the default path hook when None is stored in
753 sys.path_importer_cache."""
Brett Cannon2dee5972009-02-21 03:15:37 +0000754 return super()._path_importer_cache(path, _DEFAULT_PATH_HOOK)
Brett Cannon32732e32009-02-15 05:48:13 +0000755
756
Brett Cannone9103d22009-03-12 22:37:06 +0000757class _ImportLockContext:
758
759 """Context manager for the import lock."""
760
761 def __enter__(self):
762 """Acquire the import lock."""
763 imp.acquire_lock()
764
765 def __exit__(self, exc_type, exc_value, exc_traceback):
766 """Release the import lock regardless of any raised exceptions."""
767 imp.release_lock()
768
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000769
Brett Cannon32732e32009-02-15 05:48:13 +0000770_IMPLICIT_META_PATH = [BuiltinImporter, FrozenImporter, _DefaultPathFinder]
771
Brett Cannon7f9876c2009-02-06 02:47:33 +0000772def _gcd_import(name, package=None, level=0):
773 """Import and return the module based on its name, the package the call is
774 being made from, and the level adjustment.
775
776 This function represents the greatest common denominator of functionality
Brett Cannon2c318a12009-02-07 01:15:27 +0000777 between import_module and __import__. This includes settting __package__ if
778 the loader did not.
779
Brett Cannon7f9876c2009-02-06 02:47:33 +0000780 """
Brett Cannon2c318a12009-02-07 01:15:27 +0000781 if package:
782 if not hasattr(package, 'rindex'):
783 raise ValueError("__package__ not set to a string")
784 elif package not in sys.modules:
785 msg = ("Parent module {0!r} not loaded, cannot perform relative "
786 "import")
787 raise SystemError(msg.format(package))
788 if not name and level == 0:
789 raise ValueError("Empty module name")
Brett Cannon7f9876c2009-02-06 02:47:33 +0000790 if level > 0:
Brett Cannon2c318a12009-02-07 01:15:27 +0000791 dot = len(package)
Brett Cannon7f9876c2009-02-06 02:47:33 +0000792 for x in range(level, 1, -1):
793 try:
794 dot = package.rindex('.', 0, dot)
Brett Cannon7f9876c2009-02-06 02:47:33 +0000795 except ValueError:
Brett Cannon2c318a12009-02-07 01:15:27 +0000796 raise ValueError("attempted relative import beyond "
797 "top-level package")
798 if name:
799 name = "{0}.{1}".format(package[:dot], name)
800 else:
801 name = package[:dot]
Brett Cannon3eeaa0a2009-03-12 22:07:17 +0000802 with _ImportLockContext():
Brett Cannon7f9876c2009-02-06 02:47:33 +0000803 try:
Brett Cannon4d75fc12009-08-30 03:47:36 +0000804 module = sys.modules[name]
805 if module is None:
806 message = ("import of {} halted; "
807 "None in sys.modules".format(name))
808 raise ImportError(message)
809 return module
Brett Cannon7f9876c2009-02-06 02:47:33 +0000810 except KeyError:
811 pass
812 parent = name.rpartition('.')[0]
813 path = None
814 if parent:
815 if parent not in sys.modules:
Brett Cannon2c318a12009-02-07 01:15:27 +0000816 _gcd_import(parent)
817 # Backwards-compatibility; be nicer to skip the dict lookup.
818 parent_module = sys.modules[parent]
Brett Cannon1c1dcbf2009-08-30 20:22:21 +0000819 try:
820 path = parent_module.__path__
821 except AttributeError:
822 raise ImportError("no module named {}; "
823 "{} is not a package".format(name, parent))
Brett Cannon32732e32009-02-15 05:48:13 +0000824 meta_path = sys.meta_path + _IMPLICIT_META_PATH
Brett Cannon2c318a12009-02-07 01:15:27 +0000825 for finder in meta_path:
Brett Cannon7f9876c2009-02-06 02:47:33 +0000826 loader = finder.find_module(name, path)
Brett Cannon2c318a12009-02-07 01:15:27 +0000827 if loader is not None:
828 loader.load_module(name)
829 break
Brett Cannon7f9876c2009-02-06 02:47:33 +0000830 else:
831 raise ImportError("No module named {0}".format(name))
Brett Cannon2c318a12009-02-07 01:15:27 +0000832 # Backwards-compatibility; be nicer to skip the dict lookup.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000833 module = sys.modules[name]
834 if parent:
Brett Cannon2c318a12009-02-07 01:15:27 +0000835 # Set the module as an attribute on its parent.
836 setattr(parent_module, name.rpartition('.')[2], module)
837 # Set __package__ if the loader did not.
838 if not hasattr(module, '__package__') or module.__package__ is None:
839 # Watch out for what comes out of sys.modules to not be a module,
840 # e.g. an int.
841 try:
842 module.__package__ = module.__name__
843 if not hasattr(module, '__path__'):
844 module.__package__ = module.__package__.rpartition('.')[0]
845 except AttributeError:
846 pass
847 return module
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000848
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000849
Brett Cannon7aa21f72009-03-15 00:53:05 +0000850def __import__(name, globals={}, locals={}, fromlist=[], level=0):
Brett Cannon2c318a12009-02-07 01:15:27 +0000851 """Import a module.
852
853 The 'globals' argument is used to infer where the import is occuring from
854 to handle relative imports. The 'locals' argument is ignored. The
855 'fromlist' argument specifies what should exist as attributes on the module
856 being imported (e.g. ``from module import <fromlist>``). The 'level'
857 argument represents the package location to import from in a relative
858 import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
859
860 """
Brett Cannon6afbaef2009-08-30 19:08:58 +0000861 if not hasattr(name, 'rpartition'):
862 raise TypeError("module name must be str, not {}".format(type(name)))
Brett Cannon2c318a12009-02-07 01:15:27 +0000863 if level == 0:
864 module = _gcd_import(name)
865 else:
Brett Cannonde4ebfe2009-08-30 19:53:48 +0000866 # __package__ is not guaranteed to be defined or could be set to None
867 # to represent that it's proper value is unknown
868 package = globals.get('__package__')
869 if package is None:
Brett Cannon2c318a12009-02-07 01:15:27 +0000870 package = globals['__name__']
871 if '__path__' not in globals:
872 package = package.rpartition('.')[0]
873 module = _gcd_import(name, package, level)
874 # The hell that is fromlist ...
875 if not fromlist:
876 # Return up to the first dot in 'name'. This is complicated by the fact
877 # that 'name' may be relative.
878 if level == 0:
879 return sys.modules[name.partition('.')[0]]
880 elif not name:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000881 return module
Brett Cannon2c318a12009-02-07 01:15:27 +0000882 else:
883 cut_off = len(name) - len(name.partition('.')[0])
884 return sys.modules[module.__name__[:-cut_off]]
885 else:
886 # If a package was imported, try to import stuff from fromlist.
887 if hasattr(module, '__path__'):
888 if '*' in fromlist and hasattr(module, '__all__'):
Brett Cannon9e0e1a62009-08-30 18:28:46 +0000889 fromlist = list(fromlist)
Brett Cannon2c318a12009-02-07 01:15:27 +0000890 fromlist.remove('*')
891 fromlist.extend(module.__all__)
892 for x in (y for y in fromlist if not hasattr(module,y)):
893 try:
894 _gcd_import('{0}.{1}'.format(module.__name__, x))
895 except ImportError:
896 pass
897 return module