blob: 31f8c766381adc3c125fedcc704277b1f6fa7968 [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,
Nick Coghland5cacbb2015-05-23 22:24:10 +100011 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:
Nick Coghland5cacbb2015-05-23 22:24:10 +100014 from _imp import create_dynamic
Brett Cannoncd171c82013-07-04 17:43:24 -040015except ImportError:
Brett Cannon3e2fe052013-03-17 15:48:16 -070016 # Platform doesn't support dynamic loading.
Nick Coghland5cacbb2015-05-23 22:24:10 +100017 create_dynamic = None
Brett Cannon6f44d662012-04-15 16:08:47 -040018
Nick Coghland5cacbb2015-05-23 22:24:10 +100019from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name
Eric Snow32439d62015-05-02 19:15:18 -060020from importlib._bootstrap_external import SourcelessFileLoader
Brett Cannon01a76172012-04-15 20:25:23 -040021
Brett Cannoncb66eb02012-05-11 12:58:42 -040022from importlib import machinery
Brett Cannon05a647d2013-06-14 19:02:34 -040023from importlib import util
Brett Cannon3fe35e62013-06-14 15:04:26 -040024import importlib
Brett Cannon2ee61422012-04-15 22:28:28 -040025import os
Brett Cannone69f0df2012-04-21 21:09:46 -040026import sys
27import tokenize
Brett Cannona3c96152013-06-14 22:26:30 -040028import types
Brett Cannoncb66eb02012-05-11 12:58:42 -040029import warnings
Brett Cannone69f0df2012-04-21 21:09:46 -040030
Brett Cannone4f41de2013-06-16 13:13:40 -040031warnings.warn("the imp module is deprecated in favour of importlib; "
32 "see the module's documentation for alternative uses",
Brett Cannonc0d91af2015-10-16 12:21:37 -070033 DeprecationWarning, stacklevel=2)
Brett Cannone69f0df2012-04-21 21:09:46 -040034
Brett Cannonc0499522012-05-11 14:48:41 -040035# DEPRECATED
Brett Cannone69f0df2012-04-21 21:09:46 -040036SEARCH_ERROR = 0
37PY_SOURCE = 1
38PY_COMPILED = 2
39C_EXTENSION = 3
40PY_RESOURCE = 4
41PKG_DIRECTORY = 5
42C_BUILTIN = 6
43PY_FROZEN = 7
44PY_CODERESOURCE = 8
45IMP_HOOK = 9
Brett Cannon2ee61422012-04-15 22:28:28 -040046
47
Brett Cannona3c96152013-06-14 22:26:30 -040048def new_module(name):
49 """**DEPRECATED**
50
51 Create a new module.
52
53 The module is not entered into sys.modules.
54
55 """
56 return types.ModuleType(name)
57
58
Brett Cannon77b2abd2012-07-09 16:09:00 -040059def get_magic():
Brett Cannon05a647d2013-06-14 19:02:34 -040060 """**DEPRECATED**
61
Brett Cannonf299abd2015-04-13 14:21:02 -040062 Return the magic number for .pyc files.
Brett Cannon05a647d2013-06-14 19:02:34 -040063 """
64 return util.MAGIC_NUMBER
Brett Cannon77b2abd2012-07-09 16:09:00 -040065
66
Brett Cannon98979b82012-07-02 15:13:11 -040067def get_tag():
Brett Cannonf299abd2015-04-13 14:21:02 -040068 """Return the magic tag for .pyc files."""
Brett Cannon98979b82012-07-02 15:13:11 -040069 return sys.implementation.cache_tag
70
71
Brett Cannona38e8142013-06-14 22:35:40 -040072def cache_from_source(path, debug_override=None):
73 """**DEPRECATED**
74
Brett Cannonf299abd2015-04-13 14:21:02 -040075 Given the path to a .py file, return the path to its .pyc file.
Brett Cannona38e8142013-06-14 22:35:40 -040076
77 The .py file does not need to exist; this simply returns the path to the
Brett Cannonf299abd2015-04-13 14:21:02 -040078 .pyc file calculated as if the .py file were imported.
Brett Cannona38e8142013-06-14 22:35:40 -040079
80 If debug_override is not None, then it must be a boolean and is used in
81 place of sys.flags.optimize.
82
83 If sys.implementation.cache_tag is None then NotImplementedError is raised.
84
85 """
Brett Cannonf299abd2015-04-13 14:21:02 -040086 with warnings.catch_warnings():
87 warnings.simplefilter('ignore')
88 return util.cache_from_source(path, debug_override)
Brett Cannona38e8142013-06-14 22:35:40 -040089
90
91def source_from_cache(path):
92 """**DEPRECATED**
93
Brett Cannonf299abd2015-04-13 14:21:02 -040094 Given the path to a .pyc. file, return the path to its .py file.
Brett Cannona38e8142013-06-14 22:35:40 -040095
Brett Cannonf299abd2015-04-13 14:21:02 -040096 The .pyc file does not need to exist; this simply returns the path to
97 the .py file calculated to correspond to the .pyc file. If path does
Brett Cannona38e8142013-06-14 22:35:40 -040098 not conform to PEP 3147 format, ValueError will be raised. If
99 sys.implementation.cache_tag is None then NotImplementedError is raised.
100
101 """
102 return util.source_from_cache(path)
103
104
Brett Cannon2657df42012-05-04 15:20:40 -0400105def get_suffixes():
Brett Cannone4f41de2013-06-16 13:13:40 -0400106 """**DEPRECATED**"""
Brett Cannonac9f2f32012-08-10 13:47:54 -0400107 extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
Serhiy Storchaka6787a382013-11-23 22:12:06 +0200108 source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
Brett Cannoncb66eb02012-05-11 12:58:42 -0400109 bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
Brett Cannon2657df42012-05-04 15:20:40 -0400110
111 return extensions + source + bytecode
112
113
Brett Cannonacf85cd2012-04-29 12:50:03 -0400114class NullImporter:
115
Brett Cannone4f41de2013-06-16 13:13:40 -0400116 """**DEPRECATED**
117
118 Null import object.
119
120 """
Brett Cannonacf85cd2012-04-29 12:50:03 -0400121
122 def __init__(self, path):
123 if path == '':
124 raise ImportError('empty pathname', path='')
125 elif os.path.isdir(path):
126 raise ImportError('existing directory', path=path)
127
128 def find_module(self, fullname):
129 """Always returns None."""
130 return None
131
132
Brett Cannon64befe92012-04-17 19:14:26 -0400133class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -0400134
Zachary Ware50db6ac2015-04-14 15:43:00 -0500135 """Compatibility support for 'file' arguments of various load_*()
Brett Cannon64befe92012-04-17 19:14:26 -0400136 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -0400137
138 def __init__(self, fullname, path, file=None):
139 super().__init__(fullname, path)
140 self.file = file
141
142 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -0400143 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon938d44d2012-04-22 19:58:33 -0400144 if self.file and path == self.path:
Benjamin Petersonb0274f22018-07-06 20:41:06 -0700145 # The contract of get_data() requires us to return bytes. Reopen the
146 # file in binary mode if needed.
Brett Cannona4975a92013-08-23 11:45:57 -0400147 if not self.file.closed:
148 file = self.file
Benjamin Petersonb0274f22018-07-06 20:41:06 -0700149 if 'b' not in file.mode:
150 file.close()
151 if self.file.closed:
152 self.file = file = open(self.path, 'rb')
Brett Cannona4975a92013-08-23 11:45:57 -0400153
154 with file:
Brett Cannona4975a92013-08-23 11:45:57 -0400155 return file.read()
Brett Cannon16475ad2012-04-16 22:11:25 -0400156 else:
157 return super().get_data(path)
158
159
Brett Cannon589c4ff2013-06-14 22:29:58 -0400160class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400161
162 """Compatibility support for implementing load_source()."""
163
164
Brett Cannon16475ad2012-04-16 22:11:25 -0400165def load_source(name, pathname, file=None):
Eric Snowb523f842013-11-22 09:05:39 -0700166 loader = _LoadSourceCompatibility(name, pathname, file)
167 spec = util.spec_from_file_location(name, pathname, loader=loader)
Eric Snowb523f842013-11-22 09:05:39 -0700168 if name in sys.modules:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400169 module = _exec(spec, sys.modules[name])
Eric Snowb523f842013-11-22 09:05:39 -0700170 else:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400171 module = _load(spec)
Brett Cannon5a4c2332013-04-28 11:53:26 -0400172 # To allow reloading to potentially work, use a non-hacked loader which
173 # won't rely on a now-closed file object.
Brett Cannon589c4ff2013-06-14 22:29:58 -0400174 module.__loader__ = machinery.SourceFileLoader(name, pathname)
Eric Snowb523f842013-11-22 09:05:39 -0700175 module.__spec__.loader = module.__loader__
Brett Cannon5a4c2332013-04-28 11:53:26 -0400176 return module
Brett Cannon16475ad2012-04-16 22:11:25 -0400177
178
Brett Cannon589c4ff2013-06-14 22:29:58 -0400179class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400180
181 """Compatibility support for implementing load_compiled()."""
182
183
184def load_compiled(name, pathname, file=None):
Brett Cannone4f41de2013-06-16 13:13:40 -0400185 """**DEPRECATED**"""
Eric Snowb523f842013-11-22 09:05:39 -0700186 loader = _LoadCompiledCompatibility(name, pathname, file)
187 spec = util.spec_from_file_location(name, pathname, loader=loader)
Eric Snowb523f842013-11-22 09:05:39 -0700188 if name in sys.modules:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400189 module = _exec(spec, sys.modules[name])
Eric Snowb523f842013-11-22 09:05:39 -0700190 else:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400191 module = _load(spec)
Brett Cannon5a4c2332013-04-28 11:53:26 -0400192 # To allow reloading to potentially work, use a non-hacked loader which
193 # won't rely on a now-closed file object.
Brett Cannon589c4ff2013-06-14 22:29:58 -0400194 module.__loader__ = SourcelessFileLoader(name, pathname)
Eric Snowb523f842013-11-22 09:05:39 -0700195 module.__spec__.loader = module.__loader__
Brett Cannon5a4c2332013-04-28 11:53:26 -0400196 return module
Brett Cannon64befe92012-04-17 19:14:26 -0400197
198
Brett Cannon2ee61422012-04-15 22:28:28 -0400199def load_package(name, path):
Brett Cannone4f41de2013-06-16 13:13:40 -0400200 """**DEPRECATED**"""
Brett Cannon2ee61422012-04-15 22:28:28 -0400201 if os.path.isdir(path):
Brett Cannonc0499522012-05-11 14:48:41 -0400202 extensions = (machinery.SOURCE_SUFFIXES[:] +
203 machinery.BYTECODE_SUFFIXES[:])
Brett Cannon2ee61422012-04-15 22:28:28 -0400204 for extension in extensions:
Alexandru Ardeleanc38e32a2017-06-23 20:35:03 +0300205 init_path = os.path.join(path, '__init__' + extension)
206 if os.path.exists(init_path):
207 path = init_path
Brett Cannon2ee61422012-04-15 22:28:28 -0400208 break
209 else:
210 raise ValueError('{!r} is not a package'.format(path))
Eric Snowb523f842013-11-22 09:05:39 -0700211 spec = util.spec_from_file_location(name, path,
212 submodule_search_locations=[])
Eric Snowb523f842013-11-22 09:05:39 -0700213 if name in sys.modules:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400214 return _exec(spec, sys.modules[name])
Eric Snowb523f842013-11-22 09:05:39 -0700215 else:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400216 return _load(spec)
Brett Cannon2ee61422012-04-15 22:28:28 -0400217
Brett Cannon01a76172012-04-15 20:25:23 -0400218
219def load_module(name, file, filename, details):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400220 """**DEPRECATED**
221
222 Load a module, given information returned by find_module().
Brett Cannon01a76172012-04-15 20:25:23 -0400223
224 The module name must include the full package name, if any.
225
226 """
227 suffix, mode, type_ = details
Victor Stinner942f7a22020-03-04 18:50:22 +0100228 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
Brett Cannone4f41de2013-06-16 13:13:40 -0400229 raise ValueError('invalid file open mode {!r}'.format(mode))
230 elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
231 msg = 'file object required for import (type code {})'.format(type_)
232 raise ValueError(msg)
233 elif type_ == PY_SOURCE:
234 return load_source(name, filename, file)
235 elif type_ == PY_COMPILED:
236 return load_compiled(name, filename, file)
237 elif type_ == C_EXTENSION and load_dynamic is not None:
238 if file is None:
239 with open(filename, 'rb') as opened_file:
240 return load_dynamic(name, filename, opened_file)
Brett Cannonc0499522012-05-11 14:48:41 -0400241 else:
Brett Cannone4f41de2013-06-16 13:13:40 -0400242 return load_dynamic(name, filename, file)
243 elif type_ == PKG_DIRECTORY:
244 return load_package(name, filename)
245 elif type_ == C_BUILTIN:
246 return init_builtin(name)
247 elif type_ == PY_FROZEN:
248 return init_frozen(name)
249 else:
250 msg = "Don't know how to import {} (type code {})".format(name, type_)
251 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400252
253
254def find_module(name, path=None):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400255 """**DEPRECATED**
256
257 Search for a module.
Brett Cannone69f0df2012-04-21 21:09:46 -0400258
259 If path is omitted or None, search for a built-in, frozen or special
260 module and continue search in sys.path. The module name cannot
261 contain '.'; to search for a submodule of a package, pass the
262 submodule name and the package's __path__.
263
264 """
265 if not isinstance(name, str):
266 raise TypeError("'name' must be a str, not {}".format(type(name)))
267 elif not isinstance(path, (type(None), list)):
268 # Backwards-compatibility
Brett Cannonf76457e2016-07-15 10:58:54 -0700269 raise RuntimeError("'path' must be None or a list, "
270 "not {}".format(type(path)))
Brett Cannone69f0df2012-04-21 21:09:46 -0400271
272 if path is None:
273 if is_builtin(name):
274 return None, None, ('', '', C_BUILTIN)
275 elif is_frozen(name):
276 return None, None, ('', '', PY_FROZEN)
277 else:
278 path = sys.path
279
280 for entry in path:
281 package_directory = os.path.join(entry, name)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400282 for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
Brett Cannone69f0df2012-04-21 21:09:46 -0400283 package_file_name = '__init__' + suffix
284 file_path = os.path.join(package_directory, package_file_name)
285 if os.path.isfile(file_path):
286 return None, package_directory, ('', '', PKG_DIRECTORY)
Brett Cannone4f41de2013-06-16 13:13:40 -0400287 for suffix, mode, type_ in get_suffixes():
288 file_name = name + suffix
289 file_path = os.path.join(entry, file_name)
290 if os.path.isfile(file_path):
291 break
292 else:
293 continue
294 break # Break out of outer loop when breaking out of inner loop.
Brett Cannone69f0df2012-04-21 21:09:46 -0400295 else:
Brett Cannon589c4ff2013-06-14 22:29:58 -0400296 raise ImportError(_ERR_MSG.format(name), name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400297
298 encoding = None
Serhiy Storchaka6787a382013-11-23 22:12:06 +0200299 if 'b' not in mode:
Brett Cannone69f0df2012-04-21 21:09:46 -0400300 with open(file_path, 'rb') as file:
301 encoding = tokenize.detect_encoding(file.readline)[0]
302 file = open(file_path, mode, encoding=encoding)
303 return file, file_path, (suffix, mode, type_)
Brett Cannon62228db2012-04-29 14:38:11 -0400304
305
Brett Cannon62228db2012-04-29 14:38:11 -0400306def reload(module):
Brett Cannon3fe35e62013-06-14 15:04:26 -0400307 """**DEPRECATED**
308
309 Reload the module and return it.
Brett Cannon62228db2012-04-29 14:38:11 -0400310
311 The module must have been successfully imported before.
312
313 """
Brett Cannon3fe35e62013-06-14 15:04:26 -0400314 return importlib.reload(module)
Nick Coghland5cacbb2015-05-23 22:24:10 +1000315
316
317def init_builtin(name):
318 """**DEPRECATED**
319
320 Load and return a built-in module by name, or None is such module doesn't
321 exist
322 """
323 try:
324 return _builtin_from_name(name)
325 except ImportError:
326 return None
327
328
329if create_dynamic:
330 def load_dynamic(name, path, file=None):
331 """**DEPRECATED**
332
333 Load an extension module.
334 """
335 import importlib.machinery
336 loader = importlib.machinery.ExtensionFileLoader(name, path)
Nick Coghlan9d3c61c2015-09-05 21:05:05 +1000337
338 # Issue #24748: Skip the sys.modules check in _load_module_shim;
339 # always load new extension
340 spec = importlib.machinery.ModuleSpec(
341 name=name, loader=loader, origin=path)
342 return _load(spec)
343
Nick Coghland5cacbb2015-05-23 22:24:10 +1000344else:
345 load_dynamic = None