blob: 32e8998e5051db18b84d57a6e8185cdf5b3d6bdb [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 Cannona38e8142013-06-14 22:35:40 -040019from importlib._bootstrap import SourcelessFileLoader, _ERR_MSG
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",
32 PendingDeprecationWarning)
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
61 Return the magic number for .pyc or .pyo files.
62 """
63 return util.MAGIC_NUMBER
Brett Cannon77b2abd2012-07-09 16:09:00 -040064
65
Brett Cannon98979b82012-07-02 15:13:11 -040066def get_tag():
67 """Return the magic tag for .pyc or .pyo files."""
68 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
74 Given the path to a .py file, return the path to its .pyc/.pyo file.
75
76 The .py file does not need to exist; this simply returns the path to the
77 .pyc/.pyo file calculated as if the .py file were imported. The extension
78 will be .pyc unless sys.flags.optimize is non-zero, then it will be .pyo.
79
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 """
86 return util.cache_from_source(path, debug_override)
87
88
89def source_from_cache(path):
90 """**DEPRECATED**
91
92 Given the path to a .pyc./.pyo file, return the path to its .py file.
93
94 The .pyc/.pyo file does not need to exist; this simply returns the path to
95 the .py file calculated to correspond to the .pyc/.pyo file. If path does
96 not conform to PEP 3147 format, ValueError will be raised. If
97 sys.implementation.cache_tag is None then NotImplementedError is raised.
98
99 """
100 return util.source_from_cache(path)
101
102
Brett Cannon2657df42012-05-04 15:20:40 -0400103def get_suffixes():
Brett Cannone4f41de2013-06-16 13:13:40 -0400104 """**DEPRECATED**"""
Brett Cannonac9f2f32012-08-10 13:47:54 -0400105 extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES]
Brett Cannoncb66eb02012-05-11 12:58:42 -0400106 source = [(s, 'U', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
107 bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
Brett Cannon2657df42012-05-04 15:20:40 -0400108
109 return extensions + source + bytecode
110
111
Brett Cannonacf85cd2012-04-29 12:50:03 -0400112class NullImporter:
113
Brett Cannone4f41de2013-06-16 13:13:40 -0400114 """**DEPRECATED**
115
116 Null import object.
117
118 """
Brett Cannonacf85cd2012-04-29 12:50:03 -0400119
120 def __init__(self, path):
121 if path == '':
122 raise ImportError('empty pathname', path='')
123 elif os.path.isdir(path):
124 raise ImportError('existing directory', path=path)
125
126 def find_module(self, fullname):
127 """Always returns None."""
128 return None
129
130
Brett Cannon64befe92012-04-17 19:14:26 -0400131class _HackedGetData:
Brett Cannon16475ad2012-04-16 22:11:25 -0400132
Brett Cannon64befe92012-04-17 19:14:26 -0400133 """Compatibiilty support for 'file' arguments of various load_*()
134 functions."""
Brett Cannon16475ad2012-04-16 22:11:25 -0400135
136 def __init__(self, fullname, path, file=None):
137 super().__init__(fullname, path)
138 self.file = file
139
140 def get_data(self, path):
Brett Cannon64befe92012-04-17 19:14:26 -0400141 """Gross hack to contort loader to deal w/ load_*()'s bad API."""
Brett Cannon938d44d2012-04-22 19:58:33 -0400142 if self.file and path == self.path:
Brett Cannon16475ad2012-04-16 22:11:25 -0400143 with self.file:
144 # Technically should be returning bytes, but
145 # SourceLoader.get_code() just passed what is returned to
146 # compile() which can handle str. And converting to bytes would
147 # require figuring out the encoding to decode to and
148 # tokenize.detect_encoding() only accepts bytes.
149 return self.file.read()
150 else:
151 return super().get_data(path)
152
153
Brett Cannon589c4ff2013-06-14 22:29:58 -0400154class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400155
156 """Compatibility support for implementing load_source()."""
157
158
Brett Cannon16475ad2012-04-16 22:11:25 -0400159def load_source(name, pathname, file=None):
Brett Cannon5a4c2332013-04-28 11:53:26 -0400160 _LoadSourceCompatibility(name, pathname, file).load_module(name)
161 module = sys.modules[name]
162 # To allow reloading to potentially work, use a non-hacked loader which
163 # won't rely on a now-closed file object.
Brett Cannon589c4ff2013-06-14 22:29:58 -0400164 module.__loader__ = machinery.SourceFileLoader(name, pathname)
Brett Cannon5a4c2332013-04-28 11:53:26 -0400165 return module
Brett Cannon16475ad2012-04-16 22:11:25 -0400166
167
Brett Cannon589c4ff2013-06-14 22:29:58 -0400168class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader):
Brett Cannon64befe92012-04-17 19:14:26 -0400169
170 """Compatibility support for implementing load_compiled()."""
171
172
173def load_compiled(name, pathname, file=None):
Brett Cannone4f41de2013-06-16 13:13:40 -0400174 """**DEPRECATED**"""
Brett Cannon5a4c2332013-04-28 11:53:26 -0400175 _LoadCompiledCompatibility(name, pathname, file).load_module(name)
176 module = sys.modules[name]
177 # To allow reloading to potentially work, use a non-hacked loader which
178 # won't rely on a now-closed file object.
Brett Cannon589c4ff2013-06-14 22:29:58 -0400179 module.__loader__ = SourcelessFileLoader(name, pathname)
Brett Cannon5a4c2332013-04-28 11:53:26 -0400180 return module
Brett Cannon64befe92012-04-17 19:14:26 -0400181
182
Brett Cannon2ee61422012-04-15 22:28:28 -0400183def load_package(name, path):
Brett Cannone4f41de2013-06-16 13:13:40 -0400184 """**DEPRECATED**"""
Brett Cannon2ee61422012-04-15 22:28:28 -0400185 if os.path.isdir(path):
Brett Cannonc0499522012-05-11 14:48:41 -0400186 extensions = (machinery.SOURCE_SUFFIXES[:] +
187 machinery.BYTECODE_SUFFIXES[:])
Brett Cannon2ee61422012-04-15 22:28:28 -0400188 for extension in extensions:
189 path = os.path.join(path, '__init__'+extension)
190 if os.path.exists(path):
191 break
192 else:
193 raise ValueError('{!r} is not a package'.format(path))
Brett Cannon589c4ff2013-06-14 22:29:58 -0400194 return machinery.SourceFileLoader(name, path).load_module(name)
Brett Cannon2ee61422012-04-15 22:28:28 -0400195
Brett Cannon01a76172012-04-15 20:25:23 -0400196
197def load_module(name, file, filename, details):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400198 """**DEPRECATED**
199
200 Load a module, given information returned by find_module().
Brett Cannon01a76172012-04-15 20:25:23 -0400201
202 The module name must include the full package name, if any.
203
204 """
205 suffix, mode, type_ = details
Brett Cannone4f41de2013-06-16 13:13:40 -0400206 if mode and (not mode.startswith(('r', 'U')) or '+' in mode):
207 raise ValueError('invalid file open mode {!r}'.format(mode))
208 elif file is None and type_ in {PY_SOURCE, PY_COMPILED}:
209 msg = 'file object required for import (type code {})'.format(type_)
210 raise ValueError(msg)
211 elif type_ == PY_SOURCE:
212 return load_source(name, filename, file)
213 elif type_ == PY_COMPILED:
214 return load_compiled(name, filename, file)
215 elif type_ == C_EXTENSION and load_dynamic is not None:
216 if file is None:
217 with open(filename, 'rb') as opened_file:
218 return load_dynamic(name, filename, opened_file)
Brett Cannonc0499522012-05-11 14:48:41 -0400219 else:
Brett Cannone4f41de2013-06-16 13:13:40 -0400220 return load_dynamic(name, filename, file)
221 elif type_ == PKG_DIRECTORY:
222 return load_package(name, filename)
223 elif type_ == C_BUILTIN:
224 return init_builtin(name)
225 elif type_ == PY_FROZEN:
226 return init_frozen(name)
227 else:
228 msg = "Don't know how to import {} (type code {})".format(name, type_)
229 raise ImportError(msg, name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400230
231
232def find_module(name, path=None):
Brett Cannon0450c9e2012-06-15 19:39:06 -0400233 """**DEPRECATED**
234
235 Search for a module.
Brett Cannone69f0df2012-04-21 21:09:46 -0400236
237 If path is omitted or None, search for a built-in, frozen or special
238 module and continue search in sys.path. The module name cannot
239 contain '.'; to search for a submodule of a package, pass the
240 submodule name and the package's __path__.
241
242 """
243 if not isinstance(name, str):
244 raise TypeError("'name' must be a str, not {}".format(type(name)))
245 elif not isinstance(path, (type(None), list)):
246 # Backwards-compatibility
247 raise RuntimeError("'list' must be None or a list, "
248 "not {}".format(type(name)))
249
250 if path is None:
251 if is_builtin(name):
252 return None, None, ('', '', C_BUILTIN)
253 elif is_frozen(name):
254 return None, None, ('', '', PY_FROZEN)
255 else:
256 path = sys.path
257
258 for entry in path:
259 package_directory = os.path.join(entry, name)
Brett Cannoncb66eb02012-05-11 12:58:42 -0400260 for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]:
Brett Cannone69f0df2012-04-21 21:09:46 -0400261 package_file_name = '__init__' + suffix
262 file_path = os.path.join(package_directory, package_file_name)
263 if os.path.isfile(file_path):
264 return None, package_directory, ('', '', PKG_DIRECTORY)
Brett Cannone4f41de2013-06-16 13:13:40 -0400265 for suffix, mode, type_ in get_suffixes():
266 file_name = name + suffix
267 file_path = os.path.join(entry, file_name)
268 if os.path.isfile(file_path):
269 break
270 else:
271 continue
272 break # Break out of outer loop when breaking out of inner loop.
Brett Cannone69f0df2012-04-21 21:09:46 -0400273 else:
Brett Cannon589c4ff2013-06-14 22:29:58 -0400274 raise ImportError(_ERR_MSG.format(name), name=name)
Brett Cannone69f0df2012-04-21 21:09:46 -0400275
276 encoding = None
277 if mode == 'U':
278 with open(file_path, 'rb') as file:
279 encoding = tokenize.detect_encoding(file.readline)[0]
280 file = open(file_path, mode, encoding=encoding)
281 return file, file_path, (suffix, mode, type_)
Brett Cannon62228db2012-04-29 14:38:11 -0400282
283
Brett Cannon62228db2012-04-29 14:38:11 -0400284def reload(module):
Brett Cannon3fe35e62013-06-14 15:04:26 -0400285 """**DEPRECATED**
286
287 Reload the module and return it.
Brett Cannon62228db2012-04-29 14:38:11 -0400288
289 The module must have been successfully imported before.
290
291 """
Brett Cannon3fe35e62013-06-14 15:04:26 -0400292 return importlib.reload(module)