blob: 6d156d3115c53e248a5264a7683625ca41f030aa [file] [log] [blame]
Brett Cannon6f44d662012-04-15 16:08:47 -04001"""This module provides the components needed to build your own __import__
2function. Undocumented functions are obsolete.
3
4In most cases it is preferred you consider using the importlib module's
5functionality over this module.
6
7"""
8# (Probably) need to stay in _imp
Brett Cannon62228db2012-04-29 14:38:11 -04009from _imp import (lock_held, acquire_lock, release_lock,
Brett Cannon3e2fe052013-03-17 15:48:16 -070010 get_frozen_object, is_frozen_package,
Brett Cannon2fef4d22012-04-15 19:06:23 -040011 init_builtin, init_frozen, is_builtin, is_frozen,
Brett Cannonac9f2f32012-08-10 13:47:54 -040012 _fix_co_filename)
Brett Cannon3e2fe052013-03-17 15:48:16 -070013try:
14 from _imp import load_dynamic
15except ImportError:
16 # Platform doesn't support dynamic loading.
17 load_dynamic = None
Brett Cannon6f44d662012-04-15 16:08:47 -040018
Brett Cannon77b2abd2012-07-09 16:09:00 -040019# Directly exposed by this module
Brett Cannon17098a52012-05-04 13:52:49 -040020from importlib._bootstrap import new_module
Brett Cannona6473f92012-07-13 13:57:03 -040021from importlib._bootstrap import cache_from_source, source_from_cache
Brett Cannon01a76172012-04-15 20:25:23 -040022
Brett Cannon77b2abd2012-07-09 16:09:00 -040023
Brett Cannon2ee61422012-04-15 22:28:28 -040024from importlib import _bootstrap
Brett Cannoncb66eb02012-05-11 12:58:42 -040025from importlib import machinery
Brett Cannon2ee61422012-04-15 22:28:28 -040026import os
Brett Cannone69f0df2012-04-21 21:09:46 -040027import sys
28import tokenize
Brett Cannoncb66eb02012-05-11 12:58:42 -040029import warnings
Brett Cannone69f0df2012-04-21 21:09:46 -040030
31
Brett Cannonc0499522012-05-11 14:48:41 -040032# DEPRECATED
Brett Cannone69f0df2012-04-21 21:09:46 -040033SEARCH_ERROR = 0
34PY_SOURCE = 1
35PY_COMPILED = 2
36C_EXTENSION = 3
37PY_RESOURCE = 4
38PKG_DIRECTORY = 5
39C_BUILTIN = 6
40PY_FROZEN = 7
41PY_CODERESOURCE = 8
42IMP_HOOK = 9
Brett Cannon2ee61422012-04-15 22:28:28 -040043
44
Brett Cannon77b2abd2012-07-09 16:09:00 -040045def get_magic():
46 """Return the magic number for .pyc or .pyo files."""
47 return _bootstrap._MAGIC_BYTES
48
49
Brett Cannon98979b82012-07-02 15:13:11 -040050def get_tag():
51 """Return the magic tag for .pyc or .pyo files."""
52 return sys.implementation.cache_tag
53
54
Brett Cannon2657df42012-05-04 15:20:40 -040055def get_suffixes():
Brett Cannoncb66eb02012-05-11 12:58:42 -040056 warnings.warn('imp.get_suffixes() is deprecated; use the constants '
57 'defined on importlib.machinery instead',
58 DeprecationWarning, 2)
Brett Cannonac9f2f32012-08-10 13:47:54 -040059 extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
Brett Cannoncb66eb02012-05-11 12:58:42 -040060 source = [(s, 'U', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
61 bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
Brett Cannon2657df42012-05-04 15:20:40 -040062
63 return extensions + source + bytecode
64
65
Brett Cannonacf85cd2012-04-29 12:50:03 -040066class NullImporter:
67
68 """Null import object."""
69
70 def __init__(self, path):
71 if path == '':
72 raise ImportError('empty pathname', path='')
73 elif os.path.isdir(path):
74 raise ImportError('existing directory', path=path)
75
76 def find_module(self, fullname):
77 """Always returns None."""
78 return None
79
80
Brett Cannon64befe92012-04-17 19:14:26 -040081class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -040082
Brett Cannon64befe92012-04-17 19:14:26 -040083 """Compatibiilty support for 'file' arguments of various load_*()
84 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -040085
86 def __init__(self, fullname, path, file=None):
87 super().__init__(fullname, path)
88 self.file = file
89
90 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -040091 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon938d44d2012-04-22 19:58:33 -040092 if self.file and path == self.path:
Brett Cannon16475ad2012-04-16 22:11:25 -040093 with self.file:
94 # Technically should be returning bytes, but
95 # SourceLoader.get_code() just passed what is returned to
96 # compile() which can handle str. And converting to bytes would
97 # require figuring out the encoding to decode to and
98 # tokenize.detect_encoding() only accepts bytes.
99 return self.file.read()
100 else:
101 return super().get_data(path)
102
103
Brett Cannon938d44d2012-04-22 19:58:33 -0400104class _LoadSourceCompatibility(_HackedGetData, _bootstrap.SourceFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400105
106 """Compatibility support for implementing load_source()."""
107
108
Brett Cannon16475ad2012-04-16 22:11:25 -0400109def load_source(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400110 msg = ('imp.load_source() is deprecated; use '
111 'importlib.machinery.SourceFileLoader(name, pathname).load_module()'
112 ' instead')
113 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon5a4c2332013-04-28 11:53:26 -0400114 _LoadSourceCompatibility(name, pathname, file).load_module(name)
115 module = sys.modules[name]
116 # To allow reloading to potentially work, use a non-hacked loader which
117 # won't rely on a now-closed file object.
118 module.__loader__ = _bootstrap.SourceFileLoader(name, pathname)
119 return module
Brett Cannon16475ad2012-04-16 22:11:25 -0400120
121
Brett Cannon64befe92012-04-17 19:14:26 -0400122class _LoadCompiledCompatibility(_HackedGetData,
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200123 _bootstrap.SourcelessFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400124
125 """Compatibility support for implementing load_compiled()."""
126
127
128def load_compiled(name, pathname, file=None):
Brett Cannonc0499522012-05-11 14:48:41 -0400129 msg = ('imp.load_compiled() is deprecated; use '
130 'importlib.machinery.SourcelessFileLoader(name, pathname).'
131 'load_module() instead ')
132 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon5a4c2332013-04-28 11:53:26 -0400133 _LoadCompiledCompatibility(name, pathname, file).load_module(name)
134 module = sys.modules[name]
135 # To allow reloading to potentially work, use a non-hacked loader which
136 # won't rely on a now-closed file object.
137 module.__loader__ = _bootstrap.SourcelessFileLoader(name, pathname)
138 return module
Brett Cannon64befe92012-04-17 19:14:26 -0400139
140
Brett Cannon2ee61422012-04-15 22:28:28 -0400141def load_package(name, path):
Brett Cannonc0499522012-05-11 14:48:41 -0400142 msg = ('imp.load_package() is deprecated; use either '
143 'importlib.machinery.SourceFileLoader() or '
144 'importlib.machinery.SourcelessFileLoader() instead')
145 warnings.warn(msg, DeprecationWarning, 2)
Brett Cannon2ee61422012-04-15 22:28:28 -0400146 if os.path.isdir(path):
Brett Cannonc0499522012-05-11 14:48:41 -0400147 extensions = (machinery.SOURCE_SUFFIXES[:] +
148 machinery.BYTECODE_SUFFIXES[:])
Brett Cannon2ee61422012-04-15 22:28:28 -0400149 for extension in extensions:
150 path = os.path.join(path, '__init__'+extension)
151 if os.path.exists(path):
152 break
153 else:
154 raise ValueError('{!r} is not a package'.format(path))
Brett Cannon938d44d2012-04-22 19:58:33 -0400155 return _bootstrap.SourceFileLoader(name, path).load_module(name)
Brett Cannon2ee61422012-04-15 22:28:28 -0400156
Brett Cannon01a76172012-04-15 20:25:23 -0400157
158def load_module(name, file, filename, details):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400159 """**DEPRECATED**
160
161 Load a module, given information returned by find_module().
Brett Cannon01a76172012-04-15 20:25:23 -0400162
163 The module name must include the full package name, if any.
164
165 """
166 suffix, mode, type_ = details
Brett Cannonc0499522012-05-11 14:48:41 -0400167 with warnings.catch_warnings():
168 warnings.simplefilter('ignore')
169 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
170 raise ValueError('invalid file open mode {!r}'.format(mode))
Nick Coghlan91b9f132012-09-01 00:13:45 +1000171 elif file is None and type_ in {PY_SOURCE, PY_COMPILED, C_EXTENSION}:
Brett Cannonc0499522012-05-11 14:48:41 -0400172 msg = 'file object required for import (type code {})'.format(type_)
173 raise ValueError(msg)
174 elif type_ == PY_SOURCE:
175 return load_source(name, filename, file)
176 elif type_ == PY_COMPILED:
177 return load_compiled(name, filename, file)
Brett Cannon3e2fe052013-03-17 15:48:16 -0700178 elif type_ == C_EXTENSION and load_dynamic is not None:
Nick Coghlan91b9f132012-09-01 00:13:45 +1000179 return load_dynamic(name, filename, file)
Brett Cannonc0499522012-05-11 14:48:41 -0400180 elif type_ == PKG_DIRECTORY:
181 return load_package(name, filename)
182 elif type_ == C_BUILTIN:
183 return init_builtin(name)
184 elif type_ == PY_FROZEN:
185 return init_frozen(name)
186 else:
Nick Coghlan91b9f132012-09-01 00:13:45 +1000187 msg = "Don't know how to import {} (type code {})".format(name, type_)
Brett Cannonc0499522012-05-11 14:48:41 -0400188 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400189
190
191def find_module(name, path=None):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400192 """**DEPRECATED**
193
194 Search for a module.
Brett Cannone69f0df2012-04-21 21:09:46 -0400195
196 If path is omitted or None, search for a built-in, frozen or special
197 module and continue search in sys.path. The module name cannot
198 contain '.'; to search for a submodule of a package, pass the
199 submodule name and the package's __path__.
200
201 """
202 if not isinstance(name, str):
203 raise TypeError("'name' must be a str, not {}".format(type(name)))
204 elif not isinstance(path, (type(None), list)):
205 # Backwards-compatibility
206 raise RuntimeError("'list' must be None or a list, "
207 "not {}".format(type(name)))
208
209 if path is None:
210 if is_builtin(name):
211 return None, None, ('', '', C_BUILTIN)
212 elif is_frozen(name):
213 return None, None, ('', '', PY_FROZEN)
214 else:
215 path = sys.path
216
217 for entry in path:
218 package_directory = os.path.join(entry, name)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400219 for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
Brett Cannone69f0df2012-04-21 21:09:46 -0400220 package_file_name = '__init__' + suffix
221 file_path = os.path.join(package_directory, package_file_name)
222 if os.path.isfile(file_path):
223 return None, package_directory, ('', '', PKG_DIRECTORY)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400224 with warnings.catch_warnings():
225 warnings.simplefilter('ignore')
226 for suffix, mode, type_ in get_suffixes():
227 file_name = name + suffix
228 file_path = os.path.join(entry, file_name)
229 if os.path.isfile(file_path):
230 break
231 else:
232 continue
233 break # Break out of outer loop when breaking out of inner loop.
Brett Cannone69f0df2012-04-21 21:09:46 -0400234 else:
Brett Cannonbf7eab02012-07-09 13:24:34 -0400235 raise ImportError(_bootstrap._ERR_MSG.format(name), name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400236
237 encoding = None
238 if mode == 'U':
239 with open(file_path, 'rb') as file:
240 encoding = tokenize.detect_encoding(file.readline)[0]
241 file = open(file_path, mode, encoding=encoding)
242 return file, file_path, (suffix, mode, type_)
Brett Cannon62228db2012-04-29 14:38:11 -0400243
244
245_RELOADING = {}
246
247def reload(module):
248 """Reload the module and return it.
249
250 The module must have been successfully imported before.
251
252 """
253 if not module or type(module) != type(sys):
254 raise TypeError("reload() argument must be module")
255 name = module.__name__
256 if name not in sys.modules:
257 msg = "module {} not in sys.modules"
258 raise ImportError(msg.format(name), name=name)
259 if name in _RELOADING:
260 return _RELOADING[name]
261 _RELOADING[name] = module
262 try:
263 parent_name = name.rpartition('.')[0]
264 if parent_name and parent_name not in sys.modules:
265 msg = "parent {!r} not in sys.modules"
266 raise ImportError(msg.format(parentname), name=parent_name)
267 return module.__loader__.load_module(name)
268 finally:
269 try:
270 del _RELOADING[name]
271 except KeyError:
272 pass