Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 1 | """This module provides the components needed to build your own __import__ |
| 2 | function. Undocumented functions are obsolete. |
| 3 | |
| 4 | In most cases it is preferred you consider using the importlib module's |
| 5 | functionality over this module. |
| 6 | |
| 7 | """ |
| 8 | # (Probably) need to stay in _imp |
Brett Cannon | 62228db | 2012-04-29 14:38:11 -0400 | [diff] [blame] | 9 | from _imp import (lock_held, acquire_lock, release_lock, |
Brett Cannon | 3e2fe05 | 2013-03-17 15:48:16 -0700 | [diff] [blame] | 10 | get_frozen_object, is_frozen_package, |
Brett Cannon | 2fef4d2 | 2012-04-15 19:06:23 -0400 | [diff] [blame] | 11 | init_builtin, init_frozen, is_builtin, is_frozen, |
Brett Cannon | ac9f2f3 | 2012-08-10 13:47:54 -0400 | [diff] [blame] | 12 | _fix_co_filename) |
Brett Cannon | 3e2fe05 | 2013-03-17 15:48:16 -0700 | [diff] [blame] | 13 | try: |
| 14 | from _imp import load_dynamic |
Brett Cannon | 0a14066 | 2013-06-13 20:57:26 -0400 | [diff] [blame] | 15 | except ModuleNotFoundError: |
Brett Cannon | 3e2fe05 | 2013-03-17 15:48:16 -0700 | [diff] [blame] | 16 | # Platform doesn't support dynamic loading. |
| 17 | load_dynamic = None |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 18 | |
Brett Cannon | a38e814 | 2013-06-14 22:35:40 -0400 | [diff] [blame^] | 19 | from importlib._bootstrap import SourcelessFileLoader, _ERR_MSG |
Brett Cannon | 01a7617 | 2012-04-15 20:25:23 -0400 | [diff] [blame] | 20 | |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 21 | from importlib import machinery |
Brett Cannon | 05a647d | 2013-06-14 19:02:34 -0400 | [diff] [blame] | 22 | from importlib import util |
Brett Cannon | 3fe35e6 | 2013-06-14 15:04:26 -0400 | [diff] [blame] | 23 | import importlib |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 24 | import os |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 25 | import sys |
| 26 | import tokenize |
Brett Cannon | a3c9615 | 2013-06-14 22:26:30 -0400 | [diff] [blame] | 27 | import types |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 28 | import warnings |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 29 | |
| 30 | |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 31 | # DEPRECATED |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 32 | SEARCH_ERROR = 0 |
| 33 | PY_SOURCE = 1 |
| 34 | PY_COMPILED = 2 |
| 35 | C_EXTENSION = 3 |
| 36 | PY_RESOURCE = 4 |
| 37 | PKG_DIRECTORY = 5 |
| 38 | C_BUILTIN = 6 |
| 39 | PY_FROZEN = 7 |
| 40 | PY_CODERESOURCE = 8 |
| 41 | IMP_HOOK = 9 |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 42 | |
| 43 | |
Brett Cannon | a3c9615 | 2013-06-14 22:26:30 -0400 | [diff] [blame] | 44 | def new_module(name): |
| 45 | """**DEPRECATED** |
| 46 | |
| 47 | Create a new module. |
| 48 | |
| 49 | The module is not entered into sys.modules. |
| 50 | |
| 51 | """ |
| 52 | return types.ModuleType(name) |
| 53 | |
| 54 | |
Brett Cannon | 77b2abd | 2012-07-09 16:09:00 -0400 | [diff] [blame] | 55 | def get_magic(): |
Brett Cannon | 05a647d | 2013-06-14 19:02:34 -0400 | [diff] [blame] | 56 | """**DEPRECATED** |
| 57 | |
| 58 | Return the magic number for .pyc or .pyo files. |
| 59 | """ |
| 60 | return util.MAGIC_NUMBER |
Brett Cannon | 77b2abd | 2012-07-09 16:09:00 -0400 | [diff] [blame] | 61 | |
| 62 | |
Brett Cannon | 98979b8 | 2012-07-02 15:13:11 -0400 | [diff] [blame] | 63 | def get_tag(): |
| 64 | """Return the magic tag for .pyc or .pyo files.""" |
| 65 | return sys.implementation.cache_tag |
| 66 | |
| 67 | |
Brett Cannon | a38e814 | 2013-06-14 22:35:40 -0400 | [diff] [blame^] | 68 | def cache_from_source(path, debug_override=None): |
| 69 | """**DEPRECATED** |
| 70 | |
| 71 | Given the path to a .py file, return the path to its .pyc/.pyo file. |
| 72 | |
| 73 | The .py file does not need to exist; this simply returns the path to the |
| 74 | .pyc/.pyo file calculated as if the .py file were imported. The extension |
| 75 | will be .pyc unless sys.flags.optimize is non-zero, then it will be .pyo. |
| 76 | |
| 77 | If debug_override is not None, then it must be a boolean and is used in |
| 78 | place of sys.flags.optimize. |
| 79 | |
| 80 | If sys.implementation.cache_tag is None then NotImplementedError is raised. |
| 81 | |
| 82 | """ |
| 83 | return util.cache_from_source(path, debug_override) |
| 84 | |
| 85 | |
| 86 | def source_from_cache(path): |
| 87 | """**DEPRECATED** |
| 88 | |
| 89 | Given the path to a .pyc./.pyo file, return the path to its .py file. |
| 90 | |
| 91 | The .pyc/.pyo file does not need to exist; this simply returns the path to |
| 92 | the .py file calculated to correspond to the .pyc/.pyo file. If path does |
| 93 | not conform to PEP 3147 format, ValueError will be raised. If |
| 94 | sys.implementation.cache_tag is None then NotImplementedError is raised. |
| 95 | |
| 96 | """ |
| 97 | return util.source_from_cache(path) |
| 98 | |
| 99 | |
Brett Cannon | 2657df4 | 2012-05-04 15:20:40 -0400 | [diff] [blame] | 100 | def get_suffixes(): |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 101 | warnings.warn('imp.get_suffixes() is deprecated; use the constants ' |
| 102 | 'defined on importlib.machinery instead', |
| 103 | DeprecationWarning, 2) |
Brett Cannon | ac9f2f3 | 2012-08-10 13:47:54 -0400 | [diff] [blame] | 104 | extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES] |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 105 | source = [(s, 'U', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES] |
| 106 | bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES] |
Brett Cannon | 2657df4 | 2012-05-04 15:20:40 -0400 | [diff] [blame] | 107 | |
| 108 | return extensions + source + bytecode |
| 109 | |
| 110 | |
Brett Cannon | acf85cd | 2012-04-29 12:50:03 -0400 | [diff] [blame] | 111 | class NullImporter: |
| 112 | |
| 113 | """Null import object.""" |
| 114 | |
| 115 | def __init__(self, path): |
| 116 | if path == '': |
| 117 | raise ImportError('empty pathname', path='') |
| 118 | elif os.path.isdir(path): |
| 119 | raise ImportError('existing directory', path=path) |
| 120 | |
| 121 | def find_module(self, fullname): |
| 122 | """Always returns None.""" |
| 123 | return None |
| 124 | |
| 125 | |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 126 | class _HackedGetData: |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 127 | |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 128 | """Compatibiilty support for 'file' arguments of various load_*() |
| 129 | functions.""" |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 130 | |
| 131 | def __init__(self, fullname, path, file=None): |
| 132 | super().__init__(fullname, path) |
| 133 | self.file = file |
| 134 | |
| 135 | def get_data(self, path): |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 136 | """Gross hack to contort loader to deal w/ load_*()'s bad API.""" |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 137 | if self.file and path == self.path: |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 138 | with self.file: |
| 139 | # Technically should be returning bytes, but |
| 140 | # SourceLoader.get_code() just passed what is returned to |
| 141 | # compile() which can handle str. And converting to bytes would |
| 142 | # require figuring out the encoding to decode to and |
| 143 | # tokenize.detect_encoding() only accepts bytes. |
| 144 | return self.file.read() |
| 145 | else: |
| 146 | return super().get_data(path) |
| 147 | |
| 148 | |
Brett Cannon | 589c4ff | 2013-06-14 22:29:58 -0400 | [diff] [blame] | 149 | class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader): |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 150 | |
| 151 | """Compatibility support for implementing load_source().""" |
| 152 | |
| 153 | |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 154 | def load_source(name, pathname, file=None): |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 155 | msg = ('imp.load_source() is deprecated; use ' |
| 156 | 'importlib.machinery.SourceFileLoader(name, pathname).load_module()' |
| 157 | ' instead') |
| 158 | warnings.warn(msg, DeprecationWarning, 2) |
Brett Cannon | 5a4c233 | 2013-04-28 11:53:26 -0400 | [diff] [blame] | 159 | _LoadSourceCompatibility(name, pathname, file).load_module(name) |
| 160 | module = sys.modules[name] |
| 161 | # To allow reloading to potentially work, use a non-hacked loader which |
| 162 | # won't rely on a now-closed file object. |
Brett Cannon | 589c4ff | 2013-06-14 22:29:58 -0400 | [diff] [blame] | 163 | module.__loader__ = machinery.SourceFileLoader(name, pathname) |
Brett Cannon | 5a4c233 | 2013-04-28 11:53:26 -0400 | [diff] [blame] | 164 | return module |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 165 | |
| 166 | |
Brett Cannon | 589c4ff | 2013-06-14 22:29:58 -0400 | [diff] [blame] | 167 | class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader): |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 168 | |
| 169 | """Compatibility support for implementing load_compiled().""" |
| 170 | |
| 171 | |
| 172 | def load_compiled(name, pathname, file=None): |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 173 | msg = ('imp.load_compiled() is deprecated; use ' |
| 174 | 'importlib.machinery.SourcelessFileLoader(name, pathname).' |
| 175 | 'load_module() instead ') |
| 176 | warnings.warn(msg, DeprecationWarning, 2) |
Brett Cannon | 5a4c233 | 2013-04-28 11:53:26 -0400 | [diff] [blame] | 177 | _LoadCompiledCompatibility(name, pathname, file).load_module(name) |
| 178 | module = sys.modules[name] |
| 179 | # To allow reloading to potentially work, use a non-hacked loader which |
| 180 | # won't rely on a now-closed file object. |
Brett Cannon | 589c4ff | 2013-06-14 22:29:58 -0400 | [diff] [blame] | 181 | module.__loader__ = SourcelessFileLoader(name, pathname) |
Brett Cannon | 5a4c233 | 2013-04-28 11:53:26 -0400 | [diff] [blame] | 182 | return module |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 183 | |
| 184 | |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 185 | def load_package(name, path): |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 186 | msg = ('imp.load_package() is deprecated; use either ' |
| 187 | 'importlib.machinery.SourceFileLoader() or ' |
| 188 | 'importlib.machinery.SourcelessFileLoader() instead') |
| 189 | warnings.warn(msg, DeprecationWarning, 2) |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 190 | if os.path.isdir(path): |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 191 | extensions = (machinery.SOURCE_SUFFIXES[:] + |
| 192 | machinery.BYTECODE_SUFFIXES[:]) |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 193 | for extension in extensions: |
| 194 | path = os.path.join(path, '__init__'+extension) |
| 195 | if os.path.exists(path): |
| 196 | break |
| 197 | else: |
| 198 | raise ValueError('{!r} is not a package'.format(path)) |
Brett Cannon | 589c4ff | 2013-06-14 22:29:58 -0400 | [diff] [blame] | 199 | return machinery.SourceFileLoader(name, path).load_module(name) |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 200 | |
Brett Cannon | 01a7617 | 2012-04-15 20:25:23 -0400 | [diff] [blame] | 201 | |
| 202 | def load_module(name, file, filename, details): |
Brett Cannon | 0450c9e | 2012-06-15 19:39:06 -0400 | [diff] [blame] | 203 | """**DEPRECATED** |
| 204 | |
| 205 | Load a module, given information returned by find_module(). |
Brett Cannon | 01a7617 | 2012-04-15 20:25:23 -0400 | [diff] [blame] | 206 | |
| 207 | The module name must include the full package name, if any. |
| 208 | |
| 209 | """ |
| 210 | suffix, mode, type_ = details |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 211 | with warnings.catch_warnings(): |
| 212 | warnings.simplefilter('ignore') |
| 213 | if mode and (not mode.startswith(('r', 'U')) or '+' in mode): |
| 214 | raise ValueError('invalid file open mode {!r}'.format(mode)) |
Brett Cannon | 9d0f772 | 2013-05-03 10:37:08 -0400 | [diff] [blame] | 215 | elif file is None and type_ in {PY_SOURCE, PY_COMPILED}: |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 216 | msg = 'file object required for import (type code {})'.format(type_) |
| 217 | raise ValueError(msg) |
| 218 | elif type_ == PY_SOURCE: |
| 219 | return load_source(name, filename, file) |
| 220 | elif type_ == PY_COMPILED: |
| 221 | return load_compiled(name, filename, file) |
Brett Cannon | 3e2fe05 | 2013-03-17 15:48:16 -0700 | [diff] [blame] | 222 | elif type_ == C_EXTENSION and load_dynamic is not None: |
Brett Cannon | 9d0f772 | 2013-05-03 10:37:08 -0400 | [diff] [blame] | 223 | if file is None: |
| 224 | with open(filename, 'rb') as opened_file: |
| 225 | return load_dynamic(name, filename, opened_file) |
| 226 | else: |
| 227 | return load_dynamic(name, filename, file) |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 228 | elif type_ == PKG_DIRECTORY: |
| 229 | return load_package(name, filename) |
| 230 | elif type_ == C_BUILTIN: |
| 231 | return init_builtin(name) |
| 232 | elif type_ == PY_FROZEN: |
| 233 | return init_frozen(name) |
| 234 | else: |
Nick Coghlan | 91b9f13 | 2012-09-01 00:13:45 +1000 | [diff] [blame] | 235 | msg = "Don't know how to import {} (type code {})".format(name, type_) |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 236 | raise ImportError(msg, name=name) |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 237 | |
| 238 | |
| 239 | def find_module(name, path=None): |
Brett Cannon | 0450c9e | 2012-06-15 19:39:06 -0400 | [diff] [blame] | 240 | """**DEPRECATED** |
| 241 | |
| 242 | Search for a module. |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 243 | |
| 244 | If path is omitted or None, search for a built-in, frozen or special |
| 245 | module and continue search in sys.path. The module name cannot |
| 246 | contain '.'; to search for a submodule of a package, pass the |
| 247 | submodule name and the package's __path__. |
| 248 | |
| 249 | """ |
| 250 | if not isinstance(name, str): |
| 251 | raise TypeError("'name' must be a str, not {}".format(type(name))) |
| 252 | elif not isinstance(path, (type(None), list)): |
| 253 | # Backwards-compatibility |
| 254 | raise RuntimeError("'list' must be None or a list, " |
| 255 | "not {}".format(type(name))) |
| 256 | |
| 257 | if path is None: |
| 258 | if is_builtin(name): |
| 259 | return None, None, ('', '', C_BUILTIN) |
| 260 | elif is_frozen(name): |
| 261 | return None, None, ('', '', PY_FROZEN) |
| 262 | else: |
| 263 | path = sys.path |
| 264 | |
| 265 | for entry in path: |
| 266 | package_directory = os.path.join(entry, name) |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 267 | for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]: |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 268 | package_file_name = '__init__' + suffix |
| 269 | file_path = os.path.join(package_directory, package_file_name) |
| 270 | if os.path.isfile(file_path): |
| 271 | return None, package_directory, ('', '', PKG_DIRECTORY) |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 272 | with warnings.catch_warnings(): |
| 273 | warnings.simplefilter('ignore') |
| 274 | for suffix, mode, type_ in get_suffixes(): |
| 275 | file_name = name + suffix |
| 276 | file_path = os.path.join(entry, file_name) |
| 277 | if os.path.isfile(file_path): |
| 278 | break |
| 279 | else: |
| 280 | continue |
| 281 | break # Break out of outer loop when breaking out of inner loop. |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 282 | else: |
Brett Cannon | 589c4ff | 2013-06-14 22:29:58 -0400 | [diff] [blame] | 283 | raise ImportError(_ERR_MSG.format(name), name=name) |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 284 | |
| 285 | encoding = None |
| 286 | if mode == 'U': |
| 287 | with open(file_path, 'rb') as file: |
| 288 | encoding = tokenize.detect_encoding(file.readline)[0] |
| 289 | file = open(file_path, mode, encoding=encoding) |
| 290 | return file, file_path, (suffix, mode, type_) |
Brett Cannon | 62228db | 2012-04-29 14:38:11 -0400 | [diff] [blame] | 291 | |
| 292 | |
Brett Cannon | 62228db | 2012-04-29 14:38:11 -0400 | [diff] [blame] | 293 | def reload(module): |
Brett Cannon | 3fe35e6 | 2013-06-14 15:04:26 -0400 | [diff] [blame] | 294 | """**DEPRECATED** |
| 295 | |
| 296 | Reload the module and return it. |
Brett Cannon | 62228db | 2012-04-29 14:38:11 -0400 | [diff] [blame] | 297 | |
| 298 | The module must have been successfully imported before. |
| 299 | |
| 300 | """ |
Brett Cannon | 3fe35e6 | 2013-06-14 15:04:26 -0400 | [diff] [blame] | 301 | return importlib.reload(module) |