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 | 2fef4d2 | 2012-04-15 19:06:23 -0400 | [diff] [blame] | 10 | load_dynamic, get_frozen_object, is_frozen_package, |
| 11 | init_builtin, init_frozen, is_builtin, is_frozen, |
Brett Cannon | 2657df4 | 2012-05-04 15:20:40 -0400 | [diff] [blame] | 12 | _fix_co_filename, extension_suffixes) |
Brett Cannon | 6f44d66 | 2012-04-15 16:08:47 -0400 | [diff] [blame] | 13 | |
Brett Cannon | 77b2abd | 2012-07-09 16:09:00 -0400 | [diff] [blame] | 14 | # Directly exposed by this module |
Brett Cannon | 17098a5 | 2012-05-04 13:52:49 -0400 | [diff] [blame] | 15 | from importlib._bootstrap import new_module |
Brett Cannon | a6473f9 | 2012-07-13 13:57:03 -0400 | [diff] [blame^] | 16 | from importlib._bootstrap import cache_from_source, source_from_cache |
Brett Cannon | 01a7617 | 2012-04-15 20:25:23 -0400 | [diff] [blame] | 17 | |
Brett Cannon | 77b2abd | 2012-07-09 16:09:00 -0400 | [diff] [blame] | 18 | |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 19 | from importlib import _bootstrap |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 20 | from importlib import machinery |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 21 | import os |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 22 | import sys |
| 23 | import tokenize |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 24 | import warnings |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 25 | |
| 26 | |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 27 | # DEPRECATED |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 28 | SEARCH_ERROR = 0 |
| 29 | PY_SOURCE = 1 |
| 30 | PY_COMPILED = 2 |
| 31 | C_EXTENSION = 3 |
| 32 | PY_RESOURCE = 4 |
| 33 | PKG_DIRECTORY = 5 |
| 34 | C_BUILTIN = 6 |
| 35 | PY_FROZEN = 7 |
| 36 | PY_CODERESOURCE = 8 |
| 37 | IMP_HOOK = 9 |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 38 | |
| 39 | |
Brett Cannon | 77b2abd | 2012-07-09 16:09:00 -0400 | [diff] [blame] | 40 | def get_magic(): |
| 41 | """Return the magic number for .pyc or .pyo files.""" |
| 42 | return _bootstrap._MAGIC_BYTES |
| 43 | |
| 44 | |
Brett Cannon | 98979b8 | 2012-07-02 15:13:11 -0400 | [diff] [blame] | 45 | def get_tag(): |
| 46 | """Return the magic tag for .pyc or .pyo files.""" |
| 47 | return sys.implementation.cache_tag |
| 48 | |
| 49 | |
Brett Cannon | 2657df4 | 2012-05-04 15:20:40 -0400 | [diff] [blame] | 50 | def get_suffixes(): |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 51 | warnings.warn('imp.get_suffixes() is deprecated; use the constants ' |
| 52 | 'defined on importlib.machinery instead', |
| 53 | DeprecationWarning, 2) |
Brett Cannon | 2657df4 | 2012-05-04 15:20:40 -0400 | [diff] [blame] | 54 | extensions = [(s, 'rb', C_EXTENSION) for s in extension_suffixes()] |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 55 | source = [(s, 'U', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES] |
| 56 | bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES] |
Brett Cannon | 2657df4 | 2012-05-04 15:20:40 -0400 | [diff] [blame] | 57 | |
| 58 | return extensions + source + bytecode |
| 59 | |
| 60 | |
Brett Cannon | acf85cd | 2012-04-29 12:50:03 -0400 | [diff] [blame] | 61 | class NullImporter: |
| 62 | |
| 63 | """Null import object.""" |
| 64 | |
| 65 | def __init__(self, path): |
| 66 | if path == '': |
| 67 | raise ImportError('empty pathname', path='') |
| 68 | elif os.path.isdir(path): |
| 69 | raise ImportError('existing directory', path=path) |
| 70 | |
| 71 | def find_module(self, fullname): |
| 72 | """Always returns None.""" |
| 73 | return None |
| 74 | |
| 75 | |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 76 | class _HackedGetData: |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 77 | |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 78 | """Compatibiilty support for 'file' arguments of various load_*() |
| 79 | functions.""" |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 80 | |
| 81 | def __init__(self, fullname, path, file=None): |
| 82 | super().__init__(fullname, path) |
| 83 | self.file = file |
| 84 | |
| 85 | def get_data(self, path): |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 86 | """Gross hack to contort loader to deal w/ load_*()'s bad API.""" |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 87 | if self.file and path == self.path: |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 88 | with self.file: |
| 89 | # Technically should be returning bytes, but |
| 90 | # SourceLoader.get_code() just passed what is returned to |
| 91 | # compile() which can handle str. And converting to bytes would |
| 92 | # require figuring out the encoding to decode to and |
| 93 | # tokenize.detect_encoding() only accepts bytes. |
| 94 | return self.file.read() |
| 95 | else: |
| 96 | return super().get_data(path) |
| 97 | |
| 98 | |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 99 | class _LoadSourceCompatibility(_HackedGetData, _bootstrap.SourceFileLoader): |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 100 | |
| 101 | """Compatibility support for implementing load_source().""" |
| 102 | |
| 103 | |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 104 | def load_source(name, pathname, file=None): |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 105 | msg = ('imp.load_source() is deprecated; use ' |
| 106 | 'importlib.machinery.SourceFileLoader(name, pathname).load_module()' |
| 107 | ' instead') |
| 108 | warnings.warn(msg, DeprecationWarning, 2) |
Brett Cannon | 16475ad | 2012-04-16 22:11:25 -0400 | [diff] [blame] | 109 | return _LoadSourceCompatibility(name, pathname, file).load_module(name) |
| 110 | |
| 111 | |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 112 | class _LoadCompiledCompatibility(_HackedGetData, |
Marc-Andre Lemburg | 4fe29c9 | 2012-04-25 02:31:37 +0200 | [diff] [blame] | 113 | _bootstrap.SourcelessFileLoader): |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 114 | |
| 115 | """Compatibility support for implementing load_compiled().""" |
| 116 | |
| 117 | |
| 118 | def load_compiled(name, pathname, file=None): |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 119 | msg = ('imp.load_compiled() is deprecated; use ' |
| 120 | 'importlib.machinery.SourcelessFileLoader(name, pathname).' |
| 121 | 'load_module() instead ') |
| 122 | warnings.warn(msg, DeprecationWarning, 2) |
Brett Cannon | 64befe9 | 2012-04-17 19:14:26 -0400 | [diff] [blame] | 123 | return _LoadCompiledCompatibility(name, pathname, file).load_module(name) |
| 124 | |
| 125 | |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 126 | def load_package(name, path): |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 127 | msg = ('imp.load_package() is deprecated; use either ' |
| 128 | 'importlib.machinery.SourceFileLoader() or ' |
| 129 | 'importlib.machinery.SourcelessFileLoader() instead') |
| 130 | warnings.warn(msg, DeprecationWarning, 2) |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 131 | if os.path.isdir(path): |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 132 | extensions = (machinery.SOURCE_SUFFIXES[:] + |
| 133 | machinery.BYTECODE_SUFFIXES[:]) |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 134 | for extension in extensions: |
| 135 | path = os.path.join(path, '__init__'+extension) |
| 136 | if os.path.exists(path): |
| 137 | break |
| 138 | else: |
| 139 | raise ValueError('{!r} is not a package'.format(path)) |
Brett Cannon | 938d44d | 2012-04-22 19:58:33 -0400 | [diff] [blame] | 140 | return _bootstrap.SourceFileLoader(name, path).load_module(name) |
Brett Cannon | 2ee6142 | 2012-04-15 22:28:28 -0400 | [diff] [blame] | 141 | |
Brett Cannon | 01a7617 | 2012-04-15 20:25:23 -0400 | [diff] [blame] | 142 | |
| 143 | def load_module(name, file, filename, details): |
Brett Cannon | 0450c9e | 2012-06-15 19:39:06 -0400 | [diff] [blame] | 144 | """**DEPRECATED** |
| 145 | |
| 146 | Load a module, given information returned by find_module(). |
Brett Cannon | 01a7617 | 2012-04-15 20:25:23 -0400 | [diff] [blame] | 147 | |
| 148 | The module name must include the full package name, if any. |
| 149 | |
| 150 | """ |
| 151 | suffix, mode, type_ = details |
Brett Cannon | c049952 | 2012-05-11 14:48:41 -0400 | [diff] [blame] | 152 | with warnings.catch_warnings(): |
| 153 | warnings.simplefilter('ignore') |
| 154 | if mode and (not mode.startswith(('r', 'U')) or '+' in mode): |
| 155 | raise ValueError('invalid file open mode {!r}'.format(mode)) |
| 156 | elif file is None and type_ in {PY_SOURCE, PY_COMPILED}: |
| 157 | msg = 'file object required for import (type code {})'.format(type_) |
| 158 | raise ValueError(msg) |
| 159 | elif type_ == PY_SOURCE: |
| 160 | return load_source(name, filename, file) |
| 161 | elif type_ == PY_COMPILED: |
| 162 | return load_compiled(name, filename, file) |
| 163 | elif type_ == PKG_DIRECTORY: |
| 164 | return load_package(name, filename) |
| 165 | elif type_ == C_BUILTIN: |
| 166 | return init_builtin(name) |
| 167 | elif type_ == PY_FROZEN: |
| 168 | return init_frozen(name) |
| 169 | else: |
| 170 | msg = "Don't know how to import {} (type code {}".format(name, type_) |
| 171 | raise ImportError(msg, name=name) |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 172 | |
| 173 | |
| 174 | def find_module(name, path=None): |
Brett Cannon | 0450c9e | 2012-06-15 19:39:06 -0400 | [diff] [blame] | 175 | """**DEPRECATED** |
| 176 | |
| 177 | Search for a module. |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 178 | |
| 179 | If path is omitted or None, search for a built-in, frozen or special |
| 180 | module and continue search in sys.path. The module name cannot |
| 181 | contain '.'; to search for a submodule of a package, pass the |
| 182 | submodule name and the package's __path__. |
| 183 | |
| 184 | """ |
| 185 | if not isinstance(name, str): |
| 186 | raise TypeError("'name' must be a str, not {}".format(type(name))) |
| 187 | elif not isinstance(path, (type(None), list)): |
| 188 | # Backwards-compatibility |
| 189 | raise RuntimeError("'list' must be None or a list, " |
| 190 | "not {}".format(type(name))) |
| 191 | |
| 192 | if path is None: |
| 193 | if is_builtin(name): |
| 194 | return None, None, ('', '', C_BUILTIN) |
| 195 | elif is_frozen(name): |
| 196 | return None, None, ('', '', PY_FROZEN) |
| 197 | else: |
| 198 | path = sys.path |
| 199 | |
| 200 | for entry in path: |
| 201 | package_directory = os.path.join(entry, name) |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 202 | for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]: |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 203 | package_file_name = '__init__' + suffix |
| 204 | file_path = os.path.join(package_directory, package_file_name) |
| 205 | if os.path.isfile(file_path): |
| 206 | return None, package_directory, ('', '', PKG_DIRECTORY) |
Brett Cannon | cb66eb0 | 2012-05-11 12:58:42 -0400 | [diff] [blame] | 207 | with warnings.catch_warnings(): |
| 208 | warnings.simplefilter('ignore') |
| 209 | for suffix, mode, type_ in get_suffixes(): |
| 210 | file_name = name + suffix |
| 211 | file_path = os.path.join(entry, file_name) |
| 212 | if os.path.isfile(file_path): |
| 213 | break |
| 214 | else: |
| 215 | continue |
| 216 | break # Break out of outer loop when breaking out of inner loop. |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 217 | else: |
Brett Cannon | bf7eab0 | 2012-07-09 13:24:34 -0400 | [diff] [blame] | 218 | raise ImportError(_bootstrap._ERR_MSG.format(name), name=name) |
Brett Cannon | e69f0df | 2012-04-21 21:09:46 -0400 | [diff] [blame] | 219 | |
| 220 | encoding = None |
| 221 | if mode == 'U': |
| 222 | with open(file_path, 'rb') as file: |
| 223 | encoding = tokenize.detect_encoding(file.readline)[0] |
| 224 | file = open(file_path, mode, encoding=encoding) |
| 225 | return file, file_path, (suffix, mode, type_) |
Brett Cannon | 62228db | 2012-04-29 14:38:11 -0400 | [diff] [blame] | 226 | |
| 227 | |
| 228 | _RELOADING = {} |
| 229 | |
| 230 | def reload(module): |
| 231 | """Reload the module and return it. |
| 232 | |
| 233 | The module must have been successfully imported before. |
| 234 | |
| 235 | """ |
| 236 | if not module or type(module) != type(sys): |
| 237 | raise TypeError("reload() argument must be module") |
| 238 | name = module.__name__ |
| 239 | if name not in sys.modules: |
| 240 | msg = "module {} not in sys.modules" |
| 241 | raise ImportError(msg.format(name), name=name) |
| 242 | if name in _RELOADING: |
| 243 | return _RELOADING[name] |
| 244 | _RELOADING[name] = module |
| 245 | try: |
| 246 | parent_name = name.rpartition('.')[0] |
| 247 | if parent_name and parent_name not in sys.modules: |
| 248 | msg = "parent {!r} not in sys.modules" |
| 249 | raise ImportError(msg.format(parentname), name=parent_name) |
| 250 | return module.__loader__.load_module(name) |
| 251 | finally: |
| 252 | try: |
| 253 | del _RELOADING[name] |
| 254 | except KeyError: |
| 255 | pass |