blob: 68f00178990daecef05ecd679efa5309e8366004 [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
10# Injected modules are '_warnings', 'imp', 'sys', 'marshal', 'errno', and '_os'
11# (a.k.a. 'posix', 'nt' or 'os2').
12# 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
19# XXX Could also expose Modules/getpath.c:joinpath()
20def _path_join(*args):
21 """Replacement for os.path.join."""
22 return path_sep.join(x[:-len(path_sep)] if x.endswith(path_sep) else x
23 for x in args)
24
25
26def _path_exists(path):
27 """Replacement for os.path.exists."""
28 try:
29 _os.stat(path)
30 except OSError:
31 return False
32 else:
33 return True
34
35
36def _path_is_mode_type(path, mode):
37 """Test whether the path is the specified mode type."""
38 try:
39 stat_info = _os.stat(path)
40 except OSError:
41 return False
42 return (stat_info.st_mode & 0o170000) == mode
43
44
45# XXX Could also expose Modules/getpath.c:isfile()
46def _path_isfile(path):
47 """Replacement for os.path.isfile."""
48 return _path_is_mode_type(path, 0o100000)
49
50
51# XXX Could also expose Modules/getpath.c:isdir()
52def _path_isdir(path):
53 """Replacement for os.path.isdir."""
54 return _path_is_mode_type(path, 0o040000)
55
56
57def _path_without_ext(path, ext_type):
58 """Replacement for os.path.splitext()[0]."""
59 for suffix in suffix_list(ext_type):
60 if path.endswith(suffix):
61 return path[:-len(suffix)]
62 else:
63 raise ValueError("path is not of the specified type")
64
65
66def _path_absolute(path):
67 """Replacement for os.path.abspath."""
68 if not path:
69 path = _os.getcwd()
70 try:
71 return _os._getfullpathname(path)
72 except AttributeError:
73 if path.startswith('/'):
74 return path
75 else:
76 return _path_join(_os.getcwd(), path)
77
78
79class closing:
80
81 """Simple replacement for contextlib.closing."""
82
83 def __init__(self, obj):
84 self.obj = obj
85
86 def __enter__(self):
87 return self.obj
88
89 def __exit__(self, *args):
90 self.obj.close()
91
92
93class _BuiltinFrozenBaseLoader(object):
94
95 """Base class for meta_path loaders for built-in and frozen modules.
96
97 Subclasses must implement:
98
99 * _find(fullname:str) -> bool
100 Finder which returns whether the class can handle the module.
101
102 * _load(fullname:str) -> module
103 Loader which returns the loaded module. The check for sys.modules
104 does not need to be handled by this method.
105
106 * type_:str
107 Name of the type of module being handled. Used in error messages.
108
109 """
110
111 def find_module(self, fullname, path=None):
112 """Find a module."""
113 if not self._find(fullname):
114 return None
115 return self
116
117 def load_module(self, fullname):
118 """Load a module."""
119 try:
120 return sys.modules[fullname]
121 except KeyError:
122 pass
123 mod = self._load(fullname)
124 if not mod:
125 raise ImportError("expected {0} module not "
126 "loaded".format(self.type_))
127 return mod
128
129
130class BuiltinImporter(_BuiltinFrozenBaseLoader):
131
132 """Meta path loader for built-in modules."""
133
134 type_ = "built-in"
135
136 def __init__(self):
137 """Set the methods needed by the class.
138
139 Cannot be set at the class level because the imp module is not
140 necessarily injected until after the class is created.
141
142 """
143 self._find = imp.is_builtin
144 self._load = imp.init_builtin
145
146 def find_module(self, fullname, path=None):
147 """Try to find the built-in module.
148
149 If 'path' is ever specified then the search is considered a failure.
150
151 """
152 if path is not None:
153 return None
154 return super().find_module(fullname, path)
155
156 def load_module(self, fullname):
157 """Load a built-in module."""
158 if fullname not in sys.builtin_module_names:
159 raise ImportError("{0} is not a built-in module".format(fullname))
160 return super().load_module(fullname)
161
162
163class FrozenImporter(_BuiltinFrozenBaseLoader):
164
165 """Meta path class for importing frozen modules."""
166
167 type_ = 'frozen'
168
169 def __init__(self):
170 """Specify the methods needed by the superclass.
171
172 Because imp may not be injected until after class creation these
173 methods cannot be set at the class level.
174
175 """
176 self._find = imp.is_frozen
177 self._load = imp.init_frozen
178
179 def load_module(self, fullname):
180 """Load a frozen module."""
181 if not self.find_module(fullname):
182 raise ImportError("{0} is not a frozen module".format(fullname))
183 return super().load_module(fullname)
184
185
186class ChainedImporter(object):
187
188 """Finder that sequentially calls other finders."""
189
190 def __init__(self, *importers):
191 self._importers = importers
192
193 def find_module(self, fullname, path=None):
194 for importer in self._importers:
195 result = importer.find_module(fullname, path)
196 if result:
197 return result
198 else:
199 return None
200
201
202# XXX Don't make filesystem-specific and instead make generic for any path
203# hooks.
204def chaining_fs_path_hook(*path_hooks):
205 """Create a closure which calls the path hooks sequentially looking for
206 which path hooks can handle a path entry.
207
208
209 Passed-in path hooks work as any other path hooks, raising ImportError if
210 they cannot handle the path, otherwise returning a finder.
211
212 """
213 def chained_fs_path_hook(path_entry):
214 """Closure which sees which of the captured path hooks can handle the
215 path entry."""
216 absolute_path = _path_absolute(path_entry)
217 if not _path_isdir(absolute_path):
218 raise ImportError("only directories are supported")
219 accepted = []
220 for path_hook in path_hooks:
221 try:
222 accepted.append(path_hook(absolute_path))
223 except ImportError:
224 continue
225 if not accepted:
226 raise ImportError("no path hooks could handle %s" % path_entry)
227 return ChainedImporter(*accepted)
228 return chained_fs_path_hook
229
230
231def check_name(method):
232 """Decorator to verify that the module being requested matches the one the
233 loader can handle.
234
235 The first argument (self) must define _name which the second argument is
236 comapred against. If the comparison fails then ImportError is raised.
237
238 """
239 def inner(self, name, *args, **kwargs):
240 if self._name != name:
241 raise ImportError("loader cannot handle %s" % name)
242 return method(self, name, *args, **kwargs)
243 inner.__name__ = method.__name__
244 inner.__doc__ = method.__doc__
245 inner.__dict__.update(method.__dict__)
246 return inner
247
248
249class _ExtensionFileLoader(object):
250
251 """Loader for extension modules.
252
253 The constructor is designed to work with FileImporter.
254
255 """
256
257 def __init__(self, name, path, is_pkg):
258 """Initialize the loader.
259
260 If is_pkg is True then an exception is raised as extension modules
261 cannot be the __init__ module for an extension module.
262
263 """
264 self._name = name
265 self._path = path
266 if is_pkg:
267 raise ValueError("extension modules cannot be packages")
268
269 @check_name
270 def load_module(self, fullname):
271 """Load an extension module."""
272 assert self._name == fullname
273 try:
274 module = imp.load_dynamic(fullname, self._path)
275 module.__loader__ = self
276 return module
277 except:
278 # If an error occurred, don't leave a partially initialized module.
279 if fullname in sys.modules:
280 del sys.modules[fullname]
281 raise
282
283 @check_name
284 def is_package(self, fullname):
285 """Return False as an extension module can never be a package."""
286 return False
287
288 @check_name
289 def get_code(self, fullname):
290 """Return None as an extension module cannot create a code object."""
291 return None
292
293 @check_name
294 def get_source(self, fullname):
295 """Return None as extension modules have no source code."""
296 return None
297
298
299def suffix_list(suffix_type):
300 """Return a list of file suffixes based on the imp file type."""
301 return [suffix[0] for suffix in imp.get_suffixes()
302 if suffix[2] == suffix_type]
303
304
305# XXX Need a better name.
306def get_module(fxn):
307 """Decorator to handle selecting the proper module for load_module
308 implementations.
309
310 Decorated modules are passed the module to use instead of the module name.
311 The module is either from sys.modules if it already exists (for reloading)
312 or is a new module which has __name__ set. If any exception is raised by
313 the decorated method then __loader__, __name__, __file__, and __path__ are
314 all restored on the module to their original values.
315
316 """
317 def decorated(self, fullname):
318 module = sys.modules.get(fullname)
319 is_reload = bool(module)
320 if not is_reload:
321 # This must be done before open() is called as the 'io' module
322 # implicitly imports 'locale' and would otherwise trigger an
323 # infinite loop.
324 module = imp.new_module(fullname)
325 module.__name__ = fullname
326 sys.modules[fullname] = module
327 else:
328 original_values = {}
329 modified_attrs = ['__loader__', '__name__', '__file__', '__path__']
330 for attr in modified_attrs:
331 try:
332 original_values[attr] = getattr(module, attr)
333 except AttributeError:
334 pass
335 try:
336 return fxn(self, module)
337 except:
338 if not is_reload:
339 del sys.modules[fullname]
340 else:
341 for attr in modified_attrs:
342 if attr in original_values:
343 setattr(module, attr, original_values[attr])
344 elif hasattr(module, attr):
345 delattr(module, attr)
346 raise
347 return decorated
348
349
350class _PyFileLoader(object):
351 # XXX Still smart to have this as a separate class? Or would it work
352 # better to integrate with PyFileImporter? Could cache _is_pkg info.
353 # FileImporter can be changed to return self instead of a specific loader
354 # call. Otherwise _base_path can be calculated on the fly without issue if
355 # it is known whether a module should be treated as a path or package to
356 # minimize stat calls. Could even go as far as to stat the directory the
357 # importer is in to detect changes and then cache all the info about what
358 # files were found (if stating directories is platform-dependent).
359
360 """Load a Python source or bytecode file."""
361
362 def __init__(self, name, path, is_pkg):
363 self._name = name
364 self._is_pkg = is_pkg
365 # Figure out the base path based on whether it was source or bytecode
366 # that was found.
367 try:
368 self._base_path = _path_without_ext(path, imp.PY_SOURCE)
369 except ValueError:
370 self._base_path = _path_without_ext(path, imp.PY_COMPILED)
371
372 def _find_path(self, ext_type):
373 """Find a path from the base path and the specified extension type that
374 exists, returning None if one is not found."""
375 for suffix in suffix_list(ext_type):
376 path = self._base_path + suffix
377 if _path_exists(path):
378 return path
379 else:
380 return None
381
382 def _source_path(self):
383 """Return the path to an existing source file for the module, or None
384 if one cannot be found."""
385 # Not a property so that it is easy to override.
386 return self._find_path(imp.PY_SOURCE)
387
388 def _bytecode_path(self):
389 """Return the path to a bytecode file, or None if one does not
390 exist."""
391 # Not a property for easy overriding.
392 return self._find_path(imp.PY_COMPILED)
393
394 @check_name
395 @get_module
396 def load_module(self, module):
397 """Load a Python source or bytecode module."""
398 source_path = self._source_path()
399 bytecode_path = self._bytecode_path()
400 code_object = self.get_code(module.__name__)
401 module.__file__ = source_path if source_path else bytecode_path
402 module.__loader__ = self
403 if self._is_pkg:
404 module.__path__ = [module.__file__.rsplit(path_sep, 1)[0]]
405 module.__package__ = module.__name__
406 elif '.' in module.__name__:
407 module.__package__ = module.__name__.rsplit('.', 1)[0]
408 else:
409 module.__package__ = None
410 exec(code_object, module.__dict__)
411 return module
412
413 @check_name
414 def source_mtime(self, name):
415 """Return the modification time of the source for the specified
416 module."""
417 source_path = self._source_path()
418 if not source_path:
419 return None
420 return int(_os.stat(source_path).st_mtime)
421
422 @check_name
423 def get_source(self, fullname):
424 """Return the source for the module as a string.
425
426 Return None if the source is not available. Raise ImportError if the
427 laoder cannot handle the specified module.
428
429 """
430 source_path = self._source_path()
431 if source_path is None:
432 return None
433 import tokenize
434 with closing(_fileio_FileIO(source_path, 'r')) as file:
435 encoding, lines = tokenize.detect_encoding(file.readline)
436 # XXX Will fail when passed to compile() if the encoding is
437 # anything other than UTF-8.
438 return open(source_path, encoding=encoding).read()
439
440 @check_name
441 def read_source(self, fullname):
442 """Return the source for the specified module as bytes along with the
443 path where the source came from.
444
445 The returned path is used by 'compile' for error messages.
446
447 """
448 source_path = self._source_path()
449 if source_path is None:
450 return None
451 with closing(_fileio._FileIO(source_path, 'r')) as bytes_file:
452 return bytes_file.read(), source_path
453
454 @check_name
455 def read_bytecode(self, name):
456 """Return the magic number, timestamp, and the module bytecode for the
457 module.
458
459 Raises ImportError (just like get_source) if the laoder cannot handle
460 the module. Returns None if there is no bytecode.
461
462 """
463 path = self._bytecode_path()
464 if path is None:
465 return None
466 file = _fileio._FileIO(path, 'r')
467 try:
468 with closing(file) as bytecode_file:
469 data = bytecode_file.read()
470 return data[:4], marshal._r_long(data[4:8]), data[8:]
471 except AttributeError:
472 return None
473
474 @check_name
475 def write_bytecode(self, name, magic, timestamp, data):
476 """Write out 'data' for the specified module using the specific
477 timestamp, returning a boolean
478 signifying if the write-out actually occurred.
479
480 Raises ImportError (just like get_source) if the specified module
481 cannot be handled by the loader.
482
483 """
484 bytecode_path = self._bytecode_path()
485 if not bytecode_path:
486 bytecode_path = self._base_path + suffix_list(imp.PY_COMPILED)[0]
487 file = _fileio._FileIO(bytecode_path, 'w')
488 try:
489 with closing(file) as bytecode_file:
490 bytecode_file.write(magic)
491 bytecode_file.write(marshal._w_long(timestamp))
492 bytecode_file.write(data)
493 return True
494 except IOError as exc:
495 if exc.errno == errno.EACCES:
496 return False
497 else:
498 raise
499
500 # XXX Take an optional argument to flag whether to write bytecode?
501 @check_name
502 def get_code(self, name):
503 """Return the code object for the module.
504
505 'self' must implement:
506
507 * read_bytecode(name:str) -> (int, int, bytes) or None
508 Return the magic number, timestamp, and bytecode for the
509 module. None is returned if not bytecode is available.
510
511 * source_mtime(name:str) -> int
512 Return the last modification time for the source of the module.
513 Returns None if their is no source.
514
515 * read_source(name:str) -> (bytes, str)
516 Return the source code for the module and the path to use in
517 the call to 'compile'. Not called if source_mtime returned
518 None.
519
520 * write_bytecode(name:str, magic:bytes, timestamp:int, data:str)
521 Write out bytecode for the module with the specified magic
522 number and timestamp. Not called if sys.dont_write_bytecode is
523 True.
524
525 """
526 # XXX Care enough to make sure this call does not happen if the magic
527 # number is bad?
528 source_timestamp = self.source_mtime(name)
529 # Try to use bytecode if it is available.
530 bytecode_tuple = self.read_bytecode(name)
531 if bytecode_tuple:
532 magic, pyc_timestamp, bytecode = bytecode_tuple
533 try:
534 # Verify that the magic number is valid.
535 if imp.get_magic() != magic:
536 raise ImportError("bad magic number")
537 # Verify that the bytecode is not stale (only matters when
538 # there is source to fall back on.
539 if source_timestamp:
540 if pyc_timestamp < source_timestamp:
541 raise ImportError("bytcode is stale")
542 except ImportError:
543 # If source is available give it a shot.
544 if source_timestamp is not None:
545 pass
546 else:
547 raise
548 else:
549 # Bytecode seems fine, so try to use it.
550 # XXX If the bytecode is ill-formed, would it be beneficial to
551 # try for using source if available and issue a warning?
552 return marshal.loads(bytecode)
553 elif source_timestamp is None:
554 raise ImportError("no source or bytecode available to create code "
555 "object for {0!r}".format(name))
556 # Use the source.
557 source, source_path = self.read_source(name)
558 # Convert to universal newlines.
559 line_endings = b'\n'
560 for index, c in enumerate(source):
561 if c == ord(b'\n'):
562 break
563 elif c == ord(b'\r'):
564 line_endings = b'\r'
565 try:
566 if source[index+1] == ord(b'\n'):
567 line_endings += b'\n'
568 except IndexError:
569 pass
570 break
571 if line_endings != b'\n':
572 source = source.replace(line_endings, b'\n')
573 code_object = compile(source, source_path, 'exec', dont_inherit=True)
574 # Generate bytecode and write it out.
575 if not sys.dont_write_bytecode:
576 data = marshal.dumps(code_object)
577 self.write_bytecode(name, imp.get_magic(), source_timestamp, data)
578 return code_object
579
580 def get_data(self, path):
581 """Return the data from path as raw bytes."""
582 return _fileio._FileIO(path, 'r').read()
583
584 @check_name
585 def is_package(self, fullname):
586 """Return a boolean based on whether the module is a package.
587
588 Raises ImportError (like get_source) if the loader cannot handle the
589 package.
590
591 """
592 return self._is_pkg
593
594
595class FileImporter(object):
596
597 """Base class for file importers.
598
599 Subclasses are expected to define the following attributes:
600
601 * _suffixes
602 Sequence of file suffixes whose order will be followed.
603
604 * _possible_package
605 True if importer should check for packages.
606
607 * _loader
608 A callable that takes the module name, a file path, and whether
609 the path points to a package and returns a loader for the module
610 found at that path.
611
612 """
613
614 def __init__(self, path_entry):
615 """Initialize an importer for the passed-in sys.path entry (which is
616 assumed to have already been verified as an existing directory).
617
618 Can be used as an entry on sys.path_hook.
619
620 """
621 self._path_entry = path_entry
622
623 def find_module(self, fullname, path=None):
624 tail_module = fullname.rsplit('.', 1)[-1]
625 package_directory = None
626 if self._possible_package:
627 for ext in self._suffixes:
628 package_directory = _path_join(self._path_entry, tail_module)
629 init_filename = '__init__' + ext
630 package_init = _path_join(package_directory, init_filename)
631 if (_path_isfile(package_init) and
632 _case_ok(self._path_entry, tail_module) and
633 _case_ok(package_directory, init_filename)):
634 return self._loader(fullname, package_init, True)
635 for ext in self._suffixes:
636 file_name = tail_module + ext
637 file_path = _path_join(self._path_entry, file_name)
638 if (_path_isfile(file_path) and
639 _case_ok(self._path_entry, file_name)):
640 return self._loader(fullname, file_path, False)
641 else:
642 # Raise a warning if it matches a directory w/o an __init__ file.
643 if (package_directory is not None and
644 _path_isdir(package_directory) and
645 _case_ok(self._path_entry, tail_module)):
646 _warnings.warn("Not importing directory %s: missing __init__"
647 % package_directory, ImportWarning)
648 return None
649
650
651class ExtensionFileImporter(FileImporter):
652
653 """Importer for extension files."""
654
655 _possible_package = False
656 _loader = _ExtensionFileLoader
657
658 def __init__(self, path_entry):
659 # Assigning to _suffixes here instead of at the class level because
660 # imp is not imported at the time of class creation.
661 self._suffixes = suffix_list(imp.C_EXTENSION)
662 super(ExtensionFileImporter, self).__init__(path_entry)
663
664
665class PyFileImporter(FileImporter):
666
667 """Importer for source/bytecode files."""
668
669 _possible_package = True
670 _loader = _PyFileLoader
671
672 def __init__(self, path_entry):
673 # Lack of imp during class creation means _suffixes is set here.
674 # Make sure that Python source files are listed first! Needed for an
675 # optimization by the loader.
676 self._suffixes = suffix_list(imp.PY_SOURCE)
677 self._suffixes += suffix_list(imp.PY_COMPILED)
678 super(PyFileImporter, self).__init__(path_entry)
679
680
681class ImportLockContext(object):
682
683 """Context manager for the import lock."""
684
685 def __enter__(self):
686 """Acquire the import lock."""
687 imp.acquire_lock()
688
689 def __exit__(self, exc_type, exc_value, exc_traceback):
690 """Release the import lock regardless of any raised exceptions."""
691 imp.release_lock()
692
693
694class Import(object):
695
696 """Class that implements the __import__ interface.
697
698 Backwards compatibility is maintained by extending sys.meta_path
699 interally (for handling built-in and frozen modules) and providing a
700 default path hooks entry for extension modules, .py, and .pyc
701 files. Both are controlled during instance initialization.
702
703 """
704
705 def __init__(self, default_path_hook=None,
706 extended_meta_path=None):
707 """Store a default path hook entry and a sequence to internally extend
708 sys.meta_path by (passing in None uses default importers)."""
709 if extended_meta_path is None:
710 self.extended_meta_path = BuiltinImporter(), FrozenImporter()
711 else:
712 self.extended_meta_path = extended_meta_path
713 self.default_path_hook = default_path_hook
714 if self.default_path_hook is None:
715 # Create a handler to deal with extension modules, .py, and .pyc
716 # files. Built-in and frozen modules are handled by sys.meta_path
717 # entries.
718 importers = [ExtensionFileImporter, PyFileImporter]
719 self.default_path_hook = chaining_fs_path_hook(*importers)
720
721 def _search_meta_path(self, name, path=None):
722 """Check the importers on sys.meta_path for a loader along with the
723 extended meta path sequence stored within this instance.
724
725 The extended sys.meta_path entries are searched after the entries on
726 sys.meta_path.
727
728 """
729 for entry in (tuple(sys.meta_path) + self.extended_meta_path):
730 loader = entry.find_module(name, path)
731 if loader:
732 return loader
733 else:
734 raise ImportError("No module named %s" % name)
735
736 def _sys_path_importer(self, path_entry):
737 """Return the importer for the specified path, from
738 sys.path_importer_cache if possible.
739
740 If None is stored in sys.path_importer_cache then use the default path
741 hook.
742
743 """
744 try:
745 # See if an importer is cached.
746 importer = sys.path_importer_cache[path_entry]
747 # If None was returned, use default importer factory.
748 if importer is None:
749 return self.default_path_hook(path_entry)
750 else:
751 return importer
752 except KeyError:
753 # No cached importer found; try to get a new one from
754 # sys.path_hooks or imp.NullImporter.
755 for importer_factory in (sys.path_hooks + [imp.NullImporter]):
756 try:
757 importer = importer_factory(path_entry)
758 sys.path_importer_cache[path_entry] = importer
759 return importer
760 except ImportError:
761 continue
762 else:
763 # No importer factory on sys.path_hooks works; use the default
764 # importer factory and store None in sys.path_importer_cache.
765 try:
766 importer = self.default_path_hook(path_entry)
767 sys.path_importer_cache[path_entry] = None
768 return importer
769 except ImportError:
770 raise ImportError("no importer found for %s" % path_entry)
771
772 def _search_std_path(self, name, path=None):
773 """Check sys.path or 'path' (depending if 'path' is set) for the
774 named module and return its loader."""
775 if path:
776 search_paths = path
777 else:
778 search_paths = sys.path
779 for entry in search_paths:
780 try:
781 importer = self._sys_path_importer(entry)
782 except ImportError:
783 continue
784 loader = importer.find_module(name)
785 if loader:
786 return loader
787 else:
788 raise ImportError("No module named %s" % name)
789
790 def module_from_cache(self, name):
791 """Try to return the named module from sys.modules.
792
793 Return False if the module is not in the cache.
794 """
795 if name in sys.modules:
796 return sys.modules[name]
797 else:
798 return False
799
800 def post_import(self, module):
801 """Perform any desired post-import processing on the module."""
802 return module
803
804 def _import_module(self, name, path=None):
805 """Import the specified module with no handling of parent modules.
806
807 If None is set for a value in sys.modules (to signify that a relative
808 import was attempted and failed) then ImportError is raised.
809
810 """
811 cached_module = self.module_from_cache(name)
812 if cached_module is not False:
813 if cached_module is None:
814 raise ImportError("relative import redirect")
815 else:
816 return cached_module
817 try:
818 # Attempt to find a loader on sys.meta_path.
819 loader = self._search_meta_path(name, path)
820 except ImportError:
821 # sys.meta_path search failed. Attempt to find a loader on
822 # sys.path. If this fails then module cannot be found.
823 loader = self._search_std_path(name, path)
824 # A loader was found. It is the loader's responsibility to have put an
825 # entry in sys.modules.
826 module = self.post_import(loader.load_module(name))
827 # 'module' could be something like None.
828 if not hasattr(module, '__name__'):
829 return module
830 # Set __package__.
831 if not hasattr(module, '__package__') or module.__package__ is None:
832 if hasattr(module, '__path__'):
833 module.__package__ = module.__name__
834 elif '.' in module.__name__:
835 pkg_name = module.__name__.rsplit('.', 1)[0]
836 module.__package__ = pkg_name
837 else:
838 module.__package__ = None
839 return module
840
841
842 def _import_full_module(self, name):
843 """Import a module and set it on its parent if needed."""
844 path_list = None
845 parent_name = name.rsplit('.', 1)[0]
846 parent = None
847 if parent_name != name:
848 parent = sys.modules[parent_name]
849 try:
850 path_list = parent.__path__
851 except AttributeError:
852 pass
853 self._import_module(name, path_list)
854 module = sys.modules[name]
855 if parent:
856 tail = name.rsplit('.', 1)[-1]
857 setattr(parent, tail, module)
858
859 def _find_package(self, name, has_path):
860 """Return the package that the caller is in or None."""
861 if has_path:
862 return name
863 elif '.' in name:
864 return name.rsplit('.', 1)[0]
865 else:
866 return None
867
868 @staticmethod
869 def _resolve_name(name, package, level):
870 """Return the absolute name of the module to be imported."""
871 level -= 1
872 try:
873 if package.count('.') < level:
874 raise ValueError("attempted relative import beyond top-level "
875 "package")
876 except AttributeError:
877 raise ValueError("__package__ not set to a string")
878 base = package.rsplit('.', level)[0]
879 if name:
880 return "{0}.{1}".format(base, name)
881 else:
882 return base
883
884 def _return_module(self, absolute_name, relative_name, fromlist):
885 """Return the proper module based on what module was requested (and its
886 absolute module name), who is requesting it, and whether any specific
887 attributes were specified.
888
889 The semantics of this method revolve around 'fromlist'. When it is
890 empty, the module up to the first dot is to be returned. When the
891 module being requested is an absolute name this is simple (and
892 relative_name is an empty string). But if the requested module was
893 a relative import (as signaled by relative_name having a non-false
894 value), then the name up to the first dot in the relative name resolved
895 to an absolute name is to be returned.
896
897 When fromlist is not empty and the module being imported is a package,
898 then the values
899 in fromlist need to be checked for. If a value is not a pre-existing
900 attribute a relative import is attempted. If it fails then suppressed
901 the failure silently.
902
903 """
904 if not fromlist:
905 if relative_name:
906 absolute_base = absolute_name.rpartition(relative_name)[0]
907 relative_head = relative_name.split('.', 1)[0]
908 to_return = absolute_base + relative_head
909 else:
910 to_return = absolute_name.split('.', 1)[0]
911 return sys.modules[to_return]
912 # When fromlist is not empty, return the actual module specified in
913 # the import.
914 else:
915 module = sys.modules[absolute_name]
916 if hasattr(module, '__path__') and hasattr(module, '__name__'):
917 # When fromlist has a value and the imported module is a
918 # package, then if a name in fromlist is not found as an
919 # attribute on module, try a relative import to find it.
920 # Failure is fine and the exception is suppressed.
921 check_for = list(fromlist)
922 if '*' in check_for and hasattr(module, '__all__'):
923 check_for.extend(module.__all__)
924 for item in check_for:
925 if item == '*':
926 continue
927 if not hasattr(module, item):
928 resolved_name = self._resolve_name(item,
929 module.__name__, 1)
930 try:
931 self._import_full_module(resolved_name)
932 except ImportError:
933 pass
934 return module
935
936 def __call__(self, name, globals={}, locals={}, fromlist=[], level=0):
937 """Import a module.
938
939 The 'name' argument is the name of the module to be imported (e.g.,
940 'foo' in ``import foo`` or ``from foo import ...``).
941
942 'globals' and 'locals' are the global and local namespace dictionaries
943 of the module where the import statement appears. 'globals' is used to
944 introspect the __path__ and __name__ attributes of the module making
945 the call. 'local's is ignored.
946
947 'fromlist' lists any specific objects that are to eventually be put
948 into the namespace (e.g., ``from for.bar import baz`` would have 'baz'
949 in the fromlist, and this includes '*'). An entry of '*' will lead to
950 a check for __all__ being defined on the module. If it is defined then
951 the values in __all__ will be checked to make sure that all values are
952 attributes on the module, attempting a module import relative to 'name'
953 to set that attribute.
954
955 When 'name' is a dotted name, there are two different situations to
956 consider for the return value. One is when the fromlist is empty.
957 In this situation the import statement imports and returns the name up
958 to the first dot. All subsequent names are imported but set as
959 attributes as needed on parent modules. When fromlist is not empty
960 then the module represented by the full dotted name is returned.
961
962 'level' represents possible relative imports.
963 A value of 0 is for absolute module names. Any positive value
964 represents the number of dots listed in the relative import statement
965 (e.g. has a value of 2 for ``from .. import foo``).
966
967 """
968 if not name and level < 1:
969 raise ValueError("Empty module name")
970 is_pkg = True if '__path__' in globals else False
971 caller_name = globals.get('__name__')
972 package = globals.get('__package__')
973 if caller_name and not package:
974 package = self._find_package(caller_name, '__path__' in globals)
975 if package and package not in sys.modules:
976 if not hasattr(package, 'rsplit'):
977 raise ValueError("__package__ not set to a string")
978 msg = ("Parent module {0!r} not loaded, "
979 "cannot perform relative import")
980 raise SystemError(msg.format(package))
981 with ImportLockContext():
982 if level:
983 imported_name = self._resolve_name(name, package, level)
984 else:
985 imported_name = name
986 parent_name = imported_name.rsplit('.', 1)[0]
987 if parent_name != imported_name and parent_name not in sys.modules:
988 self.__call__(parent_name, level=0)
989 # This call will also handle setting the attribute on the
990 # package.
991 self._import_full_module(imported_name)
992 relative_name = '' if imported_name == name else name
993 return self._return_module(imported_name, relative_name, fromlist)
994
995# XXX Eventually replace with a proper __all__ value (i.e., don't expose os
996# replacements but do expose _ExtensionFileLoader, etc. for testing).
997__all__ = [obj for obj in globals().keys() if not obj.startswith('__')]