blob: 35c4a6910f7416c69dcb8042803b854064373671 [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
Brett Cannoncd171c82013-07-04 17:43:24 -040015except ImportError:
Brett Cannon3e2fe052013-03-17 15:48:16 -070016 # Platform doesn't support dynamic loading.
17 load_dynamic = None
Brett Cannon6f44d662012-04-15 16:08:47 -040018
Brett Cannon2a17bde2014-05-30 14:55:29 -040019from importlib._bootstrap import SourcelessFileLoader, _ERR_MSG, _exec, _load
Brett Cannon01a76172012-04-15 20:25:23 -040020
Brett Cannoncb66eb02012-05-11 12:58:42 -040021from importlib import machinery
Brett Cannon05a647d2013-06-14 19:02:34 -040022from importlib import util
Brett Cannon3fe35e62013-06-14 15:04:26 -040023import importlib
Brett Cannon2ee61422012-04-15 22:28:28 -040024import os
Brett Cannone69f0df2012-04-21 21:09:46 -040025import sys
26import tokenize
Brett Cannona3c96152013-06-14 22:26:30 -040027import types
Brett Cannoncb66eb02012-05-11 12:58:42 -040028import warnings
Brett Cannone69f0df2012-04-21 21:09:46 -040029
Brett Cannone4f41de2013-06-16 13:13:40 -040030warnings.warn("the imp module is deprecated in favour of importlib; "
31 "see the module's documentation for alternative uses",
Brett Cannon781692f2015-03-27 12:56:57 -040032 PendingDeprecationWarning, stacklevel=2)
Brett Cannone69f0df2012-04-21 21:09:46 -040033
Brett Cannonc0499522012-05-11 14:48:41 -040034# DEPRECATED
Brett Cannone69f0df2012-04-21 21:09:46 -040035SEARCH_ERROR = 0
36PY_SOURCE = 1
37PY_COMPILED = 2
38C_EXTENSION = 3
39PY_RESOURCE = 4
40PKG_DIRECTORY = 5
41C_BUILTIN = 6
42PY_FROZEN = 7
43PY_CODERESOURCE = 8
44IMP_HOOK = 9
Brett Cannon2ee61422012-04-15 22:28:28 -040045
46
Brett Cannona3c96152013-06-14 22:26:30 -040047def new_module(name):
48 """**DEPRECATED**
49
50 Create a new module.
51
52 The module is not entered into sys.modules.
53
54 """
55 return types.ModuleType(name)
56
57
Brett Cannon77b2abd2012-07-09 16:09:00 -040058def get_magic():
Brett Cannon05a647d2013-06-14 19:02:34 -040059 """**DEPRECATED**
60
Brett Cannonf299abd2015-04-13 14:21:02 -040061 Return the magic number for .pyc files.
Brett Cannon05a647d2013-06-14 19:02:34 -040062 """
63 return util.MAGIC_NUMBER
Brett Cannon77b2abd2012-07-09 16:09:00 -040064
65
Brett Cannon98979b82012-07-02 15:13:11 -040066def get_tag():
Brett Cannonf299abd2015-04-13 14:21:02 -040067 """Return the magic tag for .pyc files."""
Brett Cannon98979b82012-07-02 15:13:11 -040068 return sys.implementation.cache_tag
69
70
Brett Cannona38e8142013-06-14 22:35:40 -040071def cache_from_source(path, debug_override=None):
72 """**DEPRECATED**
73
Brett Cannonf299abd2015-04-13 14:21:02 -040074 Given the path to a .py file, return the path to its .pyc file.
Brett Cannona38e8142013-06-14 22:35:40 -040075
76 The .py file does not need to exist; this simply returns the path to the
Brett Cannonf299abd2015-04-13 14:21:02 -040077 .pyc file calculated as if the .py file were imported.
Brett Cannona38e8142013-06-14 22:35:40 -040078
79 If debug_override is not None, then it must be a boolean and is used in
80 place of sys.flags.optimize.
81
82 If sys.implementation.cache_tag is None then NotImplementedError is raised.
83
84 """
Brett Cannonf299abd2015-04-13 14:21:02 -040085 with warnings.catch_warnings():
86 warnings.simplefilter('ignore')
87 return util.cache_from_source(path, debug_override)
Brett Cannona38e8142013-06-14 22:35:40 -040088
89
90def source_from_cache(path):
91 """**DEPRECATED**
92
Brett Cannonf299abd2015-04-13 14:21:02 -040093 Given the path to a .pyc. file, return the path to its .py file.
Brett Cannona38e8142013-06-14 22:35:40 -040094
Brett Cannonf299abd2015-04-13 14:21:02 -040095 The .pyc file does not need to exist; this simply returns the path to
96 the .py file calculated to correspond to the .pyc file. If path does
Brett Cannona38e8142013-06-14 22:35:40 -040097 not conform to PEP 3147 format, ValueError will be raised. If
98 sys.implementation.cache_tag is None then NotImplementedError is raised.
99
100 """
101 return util.source_from_cache(path)
102
103
Brett Cannon2657df42012-05-04 15:20:40 -0400104def get_suffixes():
Brett Cannone4f41de2013-06-16 13:13:40 -0400105 """**DEPRECATED**"""
Brett Cannonac9f2f32012-08-10 13:47:54 -0400106 extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
Serhiy Storchaka6787a382013-11-23 22:12:06 +0200107 source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
Brett Cannoncb66eb02012-05-11 12:58:42 -0400108 bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
Brett Cannon2657df42012-05-04 15:20:40 -0400109
110 return extensions + source + bytecode
111
112
Brett Cannonacf85cd2012-04-29 12:50:03 -0400113class NullImporter:
114
Brett Cannone4f41de2013-06-16 13:13:40 -0400115 """**DEPRECATED**
116
117 Null import object.
118
119 """
Brett Cannonacf85cd2012-04-29 12:50:03 -0400120
121 def __init__(self, path):
122 if path == '':
123 raise ImportError('empty pathname', path='')
124 elif os.path.isdir(path):
125 raise ImportError('existing directory', path=path)
126
127 def find_module(self, fullname):
128 """Always returns None."""
129 return None
130
131
Brett Cannon64befe92012-04-17 19:14:26 -0400132class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -0400133
Brett Cannon64befe92012-04-17 19:14:26 -0400134 """Compatibiilty support for 'file' arguments of various load_*()
135 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -0400136
137 def __init__(self, fullname, path, file=None):
138 super().__init__(fullname, path)
139 self.file = file
140
141 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -0400142 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon938d44d2012-04-22 19:58:33 -0400143 if self.file and path == self.path:
Brett Cannona4975a92013-08-23 11:45:57 -0400144 if not self.file.closed:
145 file = self.file
146 else:
147 self.file = file = open(self.path, 'r')
148
149 with file:
Brett Cannon16475ad2012-04-16 22:11:25 -0400150 # Technically should be returning bytes, but
151 # SourceLoader.get_code() just passed what is returned to
152 # compile() which can handle str. And converting to bytes would
153 # require figuring out the encoding to decode to and
154 # tokenize.detect_encoding() only accepts bytes.
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:
205 path = os.path.join(path, '__init__'+extension)
206 if os.path.exists(path):
207 break
208 else:
209 raise ValueError('{!r} is not a package'.format(path))
Eric Snowb523f842013-11-22 09:05:39 -0700210 spec = util.spec_from_file_location(name, path,
211 submodule_search_locations=[])
Eric Snowb523f842013-11-22 09:05:39 -0700212 if name in sys.modules:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400213 return _exec(spec, sys.modules[name])
Eric Snowb523f842013-11-22 09:05:39 -0700214 else:
Brett Cannon2a17bde2014-05-30 14:55:29 -0400215 return _load(spec)
Brett Cannon2ee61422012-04-15 22:28:28 -0400216
Brett Cannon01a76172012-04-15 20:25:23 -0400217
218def load_module(name, file, filename, details):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400219 """**DEPRECATED**
220
221 Load a module, given information returned by find_module().
Brett Cannon01a76172012-04-15 20:25:23 -0400222
223 The module name must include the full package name, if any.
224
225 """
226 suffix, mode, type_ = details
Brett Cannone4f41de2013-06-16 13:13:40 -0400227 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
228 raise ValueError('invalid file open mode {!r}'.format(mode))
229 elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
230 msg = 'file object required for import (type code {})'.format(type_)
231 raise ValueError(msg)
232 elif type_ == PY_SOURCE:
233 return load_source(name, filename, file)
234 elif type_ == PY_COMPILED:
235 return load_compiled(name, filename, file)
236 elif type_ == C_EXTENSION and load_dynamic is not None:
237 if file is None:
238 with open(filename, 'rb') as opened_file:
239 return load_dynamic(name, filename, opened_file)
Brett Cannonc0499522012-05-11 14:48:41 -0400240 else:
Brett Cannone4f41de2013-06-16 13:13:40 -0400241 return load_dynamic(name, filename, file)
242 elif type_ == PKG_DIRECTORY:
243 return load_package(name, filename)
244 elif type_ == C_BUILTIN:
245 return init_builtin(name)
246 elif type_ == PY_FROZEN:
247 return init_frozen(name)
248 else:
249 msg = "Don't know how to import {} (type code {})".format(name, type_)
250 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400251
252
253def find_module(name, path=None):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400254 """**DEPRECATED**
255
256 Search for a module.
Brett Cannone69f0df2012-04-21 21:09:46 -0400257
258 If path is omitted or None, search for a built-in, frozen or special
259 module and continue search in sys.path. The module name cannot
260 contain '.'; to search for a submodule of a package, pass the
261 submodule name and the package's __path__.
262
263 """
264 if not isinstance(name, str):
265 raise TypeError("'name' must be a str, not {}".format(type(name)))
266 elif not isinstance(path, (type(None), list)):
267 # Backwards-compatibility
268 raise RuntimeError("'list' must be None or a list, "
269 "not {}".format(type(name)))
270
271 if path is None:
272 if is_builtin(name):
273 return None, None, ('', '', C_BUILTIN)
274 elif is_frozen(name):
275 return None, None, ('', '', PY_FROZEN)
276 else:
277 path = sys.path
278
279 for entry in path:
280 package_directory = os.path.join(entry, name)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400281 for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
Brett Cannone69f0df2012-04-21 21:09:46 -0400282 package_file_name = '__init__' + suffix
283 file_path = os.path.join(package_directory, package_file_name)
284 if os.path.isfile(file_path):
285 return None, package_directory, ('', '', PKG_DIRECTORY)
Brett Cannone4f41de2013-06-16 13:13:40 -0400286 for suffix, mode, type_ in get_suffixes():
287 file_name = name + suffix
288 file_path = os.path.join(entry, file_name)
289 if os.path.isfile(file_path):
290 break
291 else:
292 continue
293 break # Break out of outer loop when breaking out of inner loop.
Brett Cannone69f0df2012-04-21 21:09:46 -0400294 else:
Brett Cannon589c4ff2013-06-14 22:29:58 -0400295 raise ImportError(_ERR_MSG.format(name), name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400296
297 encoding = None
Serhiy Storchaka6787a382013-11-23 22:12:06 +0200298 if 'b' not in mode:
Brett Cannone69f0df2012-04-21 21:09:46 -0400299 with open(file_path, 'rb') as file:
300 encoding = tokenize.detect_encoding(file.readline)[0]
301 file = open(file_path, mode, encoding=encoding)
302 return file, file_path, (suffix, mode, type_)
Brett Cannon62228db2012-04-29 14:38:11 -0400303
304
Brett Cannon62228db2012-04-29 14:38:11 -0400305def reload(module):
Brett Cannon3fe35e62013-06-14 15:04:26 -0400306 """**DEPRECATED**
307
308 Reload the module and return it.
Brett Cannon62228db2012-04-29 14:38:11 -0400309
310 The module must have been successfully imported before.
311
312 """
Brett Cannon3fe35e62013-06-14 15:04:26 -0400313 return importlib.reload(module)