blob: b6a9f82e05f268153b50b54a45bf091c4e6afc8b [file] [log] [blame]
Brett Cannonb46a1792012-02-27 18:15:42 -05001"""A pure Python implementation of import."""
Brett Cannon3fe35e62013-06-14 15:04:26 -04002__all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload']
Brett Cannon9495f182009-03-12 22:01:40 +00003
Brett Cannon7f400e12009-01-22 22:44:04 +00004# Bootstrap help #####################################################
Nick Coghlanbe7e49f2012-07-20 23:40:09 +10005
6# Until bootstrapping is complete, DO NOT import any modules that attempt
7# to import importlib._bootstrap (directly or indirectly). Since this
8# partially initialised package would be present in sys.modules, those
9# modules would get an uninitialised copy of the source version, instead
10# of a fully initialised version (either the frozen one or the one
11# initialised below if the frozen one is not available).
12import _imp # Just the builtin component, NOT the full Python module
Brett Cannon354c26e2012-02-08 18:50:22 -050013import sys
Brett Cannon7f400e12009-01-22 22:44:04 +000014
Antoine Pitrou48114b92012-06-17 22:33:38 +020015try:
Brett Cannon53089c62012-07-04 14:03:40 -040016 import _frozen_importlib as _bootstrap
Brett Cannoncd171c82013-07-04 17:43:24 -040017except ImportError:
Antoine Pitrou48114b92012-06-17 22:33:38 +020018 from . import _bootstrap
Nick Coghlanbe7e49f2012-07-20 23:40:09 +100019 _bootstrap._setup(sys, _imp)
Antoine Pitrou48114b92012-06-17 22:33:38 +020020else:
21 # importlib._bootstrap is the built-in import, ensure we don't create
22 # a second copy of the module.
23 _bootstrap.__name__ = 'importlib._bootstrap'
24 _bootstrap.__package__ = 'importlib'
Brett Cannona00c2402014-03-21 10:58:33 -040025 try:
26 _bootstrap.__file__ = __file__.replace('__init__.py', '_bootstrap.py')
27 except NameError:
28 # __file__ is not guaranteed to be defined, e.g. if this code gets
29 # frozen by a tool like cx_Freeze.
30 pass
Antoine Pitrou48114b92012-06-17 22:33:38 +020031 sys.modules['importlib._bootstrap'] = _bootstrap
32
Eric Snow32439d62015-05-02 19:15:18 -060033try:
34 import _frozen_importlib_external as _bootstrap_external
35except ImportError:
36 from . import _bootstrap_external
37 _bootstrap_external._setup(_bootstrap)
Eric Snow183a9412015-05-15 21:54:59 -060038 _bootstrap._bootstrap_external = _bootstrap_external
Eric Snow32439d62015-05-02 19:15:18 -060039else:
40 _bootstrap_external.__name__ = 'importlib._bootstrap_external'
41 _bootstrap_external.__package__ = 'importlib'
42 try:
43 _bootstrap_external.__file__ = __file__.replace('__init__.py', '_bootstrap_external.py')
44 except NameError:
45 # __file__ is not guaranteed to be defined, e.g. if this code gets
46 # frozen by a tool like cx_Freeze.
47 pass
48 sys.modules['importlib._bootstrap_external'] = _bootstrap_external
49
Antoine Pitrou48114b92012-06-17 22:33:38 +020050# To simplify imports in test code
Eric Snow32439d62015-05-02 19:15:18 -060051_w_long = _bootstrap_external._w_long
52_r_long = _bootstrap_external._r_long
Brett Cannon23cbd8a2009-01-18 00:24:28 +000053
Nick Coghlanbe7e49f2012-07-20 23:40:09 +100054# Fully bootstrapped at this point, import whatever you like, circular
55# dependencies and startup overhead minimisation permitting :)
Brett Cannonafccd632009-01-20 02:21:27 +000056
Eric Snow6029e082014-01-25 15:32:46 -070057import types
58import warnings
59
60
Brett Cannon7f400e12009-01-22 22:44:04 +000061# Public API #########################################################
62
Brett Cannonb46a1792012-02-27 18:15:42 -050063from ._bootstrap import __import__
64
65
66def invalidate_caches():
Brett Cannonf4dc9202012-08-10 12:21:12 -040067 """Call the invalidate_caches() method on all meta path finders stored in
68 sys.meta_path (where implemented)."""
69 for finder in sys.meta_path:
Brett Cannonb46a1792012-02-27 18:15:42 -050070 if hasattr(finder, 'invalidate_caches'):
71 finder.invalidate_caches()
Brett Cannonafccd632009-01-20 02:21:27 +000072
73
Eric Snowb523f842013-11-22 09:05:39 -070074def find_loader(name, path=None):
75 """Return the loader for the specified module.
76
77 This is a backward-compatible wrapper around find_spec().
Brett Cannonee78a2b2012-05-12 17:43:17 -040078
Eric Snow6029e082014-01-25 15:32:46 -070079 This function is deprecated in favor of importlib.util.find_spec().
Eric Snow1500d492014-01-06 20:49:04 -070080
Brett Cannonee78a2b2012-05-12 17:43:17 -040081 """
Eric Snow6029e082014-01-25 15:32:46 -070082 warnings.warn('Use importlib.util.find_spec() instead.',
83 DeprecationWarning, stacklevel=2)
Brett Cannonee78a2b2012-05-12 17:43:17 -040084 try:
85 loader = sys.modules[name].__loader__
86 if loader is None:
87 raise ValueError('{}.__loader__ is None'.format(name))
88 else:
89 return loader
90 except KeyError:
91 pass
Brett Cannon32799232013-03-13 11:09:08 -070092 except AttributeError:
Serhiy Storchakac4464052014-11-21 20:33:57 +020093 raise ValueError('{}.__loader__ is not set'.format(name)) from None
Eric Snowb523f842013-11-22 09:05:39 -070094
95 spec = _bootstrap._find_spec(name, path)
96 # We won't worry about malformed specs (missing attributes).
97 if spec is None:
98 return None
99 if spec.loader is None:
100 if spec.submodule_search_locations is None:
101 raise ImportError('spec for {} missing loader'.format(name),
102 name=name)
103 raise ImportError('namespace packages do not have loaders',
104 name=name)
105 return spec.loader
Brett Cannonee78a2b2012-05-12 17:43:17 -0400106
107
Brett Cannonafccd632009-01-20 02:21:27 +0000108def import_module(name, package=None):
109 """Import a module.
110
111 The 'package' argument is required when performing a relative import. It
112 specifies the package to use as the anchor point from which to resolve the
113 relative import to an absolute import.
114
115 """
Brett Cannon2c318a12009-02-07 01:15:27 +0000116 level = 0
Brett Cannonafccd632009-01-20 02:21:27 +0000117 if name.startswith('.'):
118 if not package:
Brett Cannone1f15972013-08-12 13:29:11 -0400119 msg = ("the 'package' argument is required to perform a relative "
120 "import for {!r}")
121 raise TypeError(msg.format(name))
Brett Cannonafccd632009-01-20 02:21:27 +0000122 for character in name:
123 if character != '.':
124 break
125 level += 1
Brett Cannon2c318a12009-02-07 01:15:27 +0000126 return _bootstrap._gcd_import(name[level:], package, level)
Brett Cannon3fe35e62013-06-14 15:04:26 -0400127
128
129_RELOADING = {}
130
131
132def reload(module):
133 """Reload the module and return it.
134
135 The module must have been successfully imported before.
136
137 """
138 if not module or not isinstance(module, types.ModuleType):
139 raise TypeError("reload() argument must be module")
Eric Snowb523f842013-11-22 09:05:39 -0700140 try:
141 name = module.__spec__.name
142 except AttributeError:
143 name = module.__name__
144
Eric Snowcdf60122013-10-31 22:22:15 -0600145 if sys.modules.get(name) is not module:
Brett Cannon3fe35e62013-06-14 15:04:26 -0400146 msg = "module {} not in sys.modules"
147 raise ImportError(msg.format(name), name=name)
148 if name in _RELOADING:
149 return _RELOADING[name]
150 _RELOADING[name] = module
151 try:
152 parent_name = name.rpartition('.')[0]
Eric Snowc1e7c742013-12-09 19:59:10 -0700153 if parent_name:
154 try:
155 parent = sys.modules[parent_name]
156 except KeyError:
157 msg = "parent {!r} not in sys.modules"
Serhiy Storchakac4464052014-11-21 20:33:57 +0200158 raise ImportError(msg.format(parent_name),
159 name=parent_name) from None
Eric Snowc1e7c742013-12-09 19:59:10 -0700160 else:
161 pkgpath = parent.__path__
162 else:
163 pkgpath = None
Eric Snow6029e082014-01-25 15:32:46 -0700164 target = module
165 spec = module.__spec__ = _bootstrap._find_spec(name, pkgpath, target)
Brett Cannon2a17bde2014-05-30 14:55:29 -0400166 _bootstrap._exec(spec, module)
Eric Snow8e455402013-08-14 18:11:09 -0600167 # The module may have replaced itself in sys.modules!
Eric Snowb523f842013-11-22 09:05:39 -0700168 return sys.modules[name]
Brett Cannon3fe35e62013-06-14 15:04:26 -0400169 finally:
170 try:
171 del _RELOADING[name]
172 except KeyError:
173 pass